简体   繁体   English

request.user在Django中引用了什么?

[英]What does request.user refer to in Django?

I have confusion regarding what does request.user refers to in Django? 关于request.user在Django中引用了什么,我感到很困惑? Does it refer to username field in the auth_user table or does it refer to User model instance? 它是指auth_user表中的用户 名字段还是引用用户模型实例?

I had this doubt because I was not able to access email field in the template using {{request.user.username}} or {{user.username}} . 我有这个疑问,因为我无法使用{{request.user.username}}{{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 }} . 并将userr传递给模板并以{{ userr.email }}访问了电子邮件字段。

Although its working but I wanted to have some clarity about it. 虽然它的工作,但我想对它有一些清晰度。

request.user is User model object. request.user是用户模型对象。

You cannot access request object in template if you do not pass request explicitly. 如果未明确传递request则无法访问模板中的请求对象。 If you want access user object from template, you should pass it to template or use RequestContext. 如果要从模板访问用户对象,则应将其传递给模板或使用RequestContext。

If your template is receiving AnonymousUser , the reference to {{request.user.email}} will not be found. 如果您的模板正在接收AnonymousUser ,则无法找到对{{request.user.email}}的引用。 Previously, you must ask if {{request.user.is_authenticated }} . 以前,您必须询问{{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. 您必须检查它是否包含在TEMPLATE_CONTEXT_PROCESSORS设置部分中的django.core.context_processors.auth上下文处理器。 If you are using Django 1.4 or latest, then context processor is django.contrib.auth.context_processors.auth . 如果您使用的是Django 1.4或最新版本,则上下文处理器为django.contrib.auth.context_processors.auth This context processor is responsible to include user object in every request. 此上下文处理器负责在每个请求中包含用户对象。

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 实际上,如果将'django.core.context_processors.request'附加到settings.pyTEMPLATE_CONTEXT_PROCESSORS列表中,则无需定义此类变量。

Then you can access the variable {{ request.user.username }} in templates if you are using render in views.py 然后,如果在views.py中使用render ,则可以在模板中访问变量{{request.user.username}}

request.user refers to the actual user model instance. request.user是指实际的用户模型实例。

request.user.FIELDNAME will allow you to access all the fields of the user model request.user.FIELDNAME将允许您访问用户模型的所有字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM