What does request.user refer to in Django?

冷暖自知 提交于 2019-12-21 06:51:03

问题


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.


回答1:


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.




回答2:


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.




回答3:


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




回答4:


request.user refers to the actual user model instance.

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



来源:https://stackoverflow.com/questions/17312831/what-does-request-user-refer-to-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!