Home > Net >  How to get current user data in django
How to get current user data in django

Time:06-11

I'm trying to get logged user data but I get an only username

I try these codes

 user= User.objects.get(id=user_id)
 user= User.objects.filter(id=emp_data.user_id).first()
 user =request.user

this 3 query returns username

how can i get user details

CodePudding user response:

Try this:

user = User.objects.get(id=user_id)
print(user.__dict__)

This`ll give you all attributes of User class

CodePudding user response:

These queries don’t return the username they actually return a User object. You can access the object attributes like user.name user.email etc

CodePudding user response:

Probably you are using print() function to print the object, hence you are seeing the username. This username comes from this implementation (source on GitHub):

def __str__(self):
    return self.get_username()

Where get_username() method returns username, and print executes __str__ function. If you want to see more properties or methods of the object, either use print(dir(user)) or debug using your IDE (or with pdb). You can see the type of object by type(user) function.

CodePudding user response:

You can try:

def user_information(request, pk):
    user_infor = get_objects_or_404(User, id=pk)
    return render(request, 'infor.html', {'user_infor':user_infor})

And in your infor.html you can get user information by:

<p>{{user_infor.user.email}}</p>
<p>{{user_infor.user.username}}</p>
  • Related