Dimitris
Dimitris

Reputation: 413

What is the difference between request.user and request.user.username?

As title says, what is the difference between request.user and request.user.username? I use them to compare them with some variables and sometimes it works using the first and sometimes using the second

Upvotes: 1

Views: 3812

Answers (2)

Alasdair
Alasdair

Reputation: 308999

request.user is the User instance, request.user.username is a string of that user's username.

If you have a string, e.g. 'admin', then you would want to compare it to the request.user.username.

Upvotes: 5

Павел Тявин
Павел Тявин

Reputation: 2659

I think that questions comes only after you were using user objects in your templates like {{user}} and {{user.username}} and understand that templates rendering the same.

The point is that when you render the template, django automatically converts variables to its unicode representation (strings), and in your view function it can be not a string but an instance of some model.

User class from app django.contrib.auth has a unicode representation like

def __unicode__(self):
    return self.username

And maybe that's why you were confusing user and user.username .

This misunderstanding can be dangerous, cause when you are typing something like

if user1 == user2.username:

you won't get TypeError, cause any django model inhereted from models.Model has a operator

def __eq__(self, other):
    return isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val()

which finds if user1 and user2.username had the same class.

Anyway, I think after practicing a little you'll find difference between string and objects of some model.


Upvotes: 4

Related Questions