What does request.user refer to in Django?

Question:

I have confusion regarding what does request.user refers to in Django?
Does it refer to username field in the auth_user table or does it refer to User model instance?

I had this doubt because I was not able to access email field in the template using {{request.user.username}} or {{user.username}}.

So instead I did following in views file:

userr = User.objects.get(username=request.user)

And passed userr to the template and accessed email field as {{ userr.email }}.

Although its working but I wanted to have some clarity about it.

Asked By: zephyr

||

Answers:

request.user refers to the actual user model instance.

request.user.FIELDNAME will allow you to access all the fields of the user model

Answered By: jammas615

request.user is User model object.

You cannot access request object in template if you do not pass request explicitly.
If you want access user object from template, you should pass it to template or use RequestContext.

Answered By: falsetru

If your template is receiving AnonymousUser, the reference to {{request.user.email}} will not be found. Previously, you must ask if {{request.user.is_authenticated }}.

You must check if it is included django.core.context_processors.auth context processor in TEMPLATE_CONTEXT_PROCESSORS section of settings. If you are using Django 1.4 or latest, then context processor is django.contrib.auth.context_processors.auth. This context processor is responsible to include user object in every request.

Answered By: emigue

It depends upon what you set .

So, it is better to use

user = User.objects.get(username=request.user.username)

Actually, you don’t need to define such variables if you append 'django.core.context_processors.request' into the TEMPLATE_CONTEXT_PROCESSORS list in settings.py

Then you can access the variable {{ request.user.username }} in templates if you are using render in views.py

Answered By: suhailvs