Gehad Al Sayed
Gehad Al Sayed

Reputation: 13

how can i display other user information in django

I'm creating a website that the user can look at other users profile but the problem is when the user enter another user profile it show his personal information

this is the urls.py file code

urlpatterns = [
    path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
]

this is the view.py file code

class UserPostListView(ListView):
    model = Post = Profile
    template_name = 'website/user_posts.html'

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user)

    def get_username_field(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Profile.objects.filter(user=user)

this is the models.py file

class Profile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)

    age = models.IntegerField(verbose_name='Ålder', default=15, 
    blank=True)

    def get_absolute_url(self):
        return reverse('user_posts', kwargs={'pk': self.pk})

    def __str__(self):
        return f'{self.user.username} Profile'

user_posts.html file

{{ user.get_full_name }}
{{ user.profile.age }}
{{ view.kwargs.username }}

in the template it's show the username but it didnt' show the name and the age.

Upvotes: 1

Views: 1693

Answers (2)

Bidhan Majhi
Bidhan Majhi

Reputation: 1370

First of all your get_username_field is of no use.

In your views.py,

class UserPostListView(ListView):
    model = Profile
    template_name = 'website/user_posts.html'
    context_object_name = 'user_content'  
    allow_empty = False  #this will show 404 if the username does not exists

    def get_queryset(self):
        return User.objects.filter(username=self.kwargs['username']) 
        # you can do it in one line now 

Now to show this in html,

{% for user in user_content %}
{{user.get_full_name}}
# rest of your code
{% endfor %}

You can also show posts of that particular user in same way as above.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599480

user is always the current logged-in user. Your view uses the Profile model, so you can either access profile or object.

{{ profile.user.get_full_name }}
{{ profile.age }}

Note, your get_username_field method is never called and does not do anything; you should remove it.

Note also, it's really not a good idea to store age as an integer in the database. That means you somehow have to update it every year, as people have a strange habit of getting older... Better to store the date of birth, and have a method to display the age.

Upvotes: 3

Related Questions