Home > Software engineering >  Accessing User objects through User.objects.filter for a profile page
Accessing User objects through User.objects.filter for a profile page

Time:05-24

How can i query User model to get user informations like: username, email, first name, and last name into his profile. I want to display all these information in his profile page.

as you can see here in the Profle view i'm willing to access user email, but how can i query the database to get all these information in the profile page ?

def profile(request, pk):
    user_profile = User.objects.filter(email=request.user)


    context = {'user_profile':user_profile}
    return render(request, 'profile.html', context)

the profile template:

  <p>{{user.email}}</p>

CodePudding user response:

If you want to access only current logged in user information so you should not use filter() as it gives you queryset and used via loops which we run in templates. You should use get_object_or_404[django-doc] for displaying data of single object. It gives 404 if found nothing.

Views.py

from django.shortcuts import get_object_or_404

def profile(request, pk):
    single_user = get_object_or_404(User,id=request.user.id)


    context = {'single_user':single_user}
    return render(request, 'profile.html', context)

Template file


{% if single_user %}
    <p>Email : {{single_user.email}}</p>

    <p>Username: {{single_user.username}}</p>
    <p>first name : {{single_user.first_name}}</p>
    <p>last name: {{single_user.last_name}}</p>
{% else %}
    <p>user is not coming</p>
{% endif %}

CodePudding user response:

If you are looking for the logged_in user details, you already have that as part of the request object. So you can use the following in your template without doing a lookup in your view:

<p>Username: {{request.user.username}}</p>
<p>Email: {{request.user.email}}</p>

If you want to use the PK value being passed to your view, so that a visitor can visit the profile of another user (eg, the Primary Key is to identify another user account) you can do a lookup on that. As Sunderam Dubey notes, the best method for that is via a get_object_or_404() call in your view

views.py

from django.shortcuts import get_object_or_404

def profile(request, pk):
    user = get_object_or_404(User,id=pk)     
    context = {'user_context':user}
    return render(request, 'profile.html', context)
 

profile.html

<p>Email : {{user_context.email}}</p>
<p>Username : {{user_context.username}}</p>

Note the variable object names with _context at the end. You don't have to follow this naming convention, but what's important is that the things I have named 'user_context' have the same name.

  • Related