28

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.

4

4 回答 4

16

request.user是用户模型对象。

如果您不request明确传递,则无法访问模板中的请求对象。如果你想从模板访问用户对象,你应该将它传递给模板或使用 RequestContext。

于 2013-06-26T06:24:47.347 回答
15

如果您的模板正在接收AnonymousUser{{request.user.email}}则不会找到对的引用。以前,您必须询问是否{{request.user.is_authenticated }}.

您必须检查它是否包含在设置部分中的django.core.context_processors.auth上下文处理器中。TEMPLATE_CONTEXT_PROCESSORS如果您使用的是 Django 1.4 或最新版本,那么上下文处理器是django.contrib.auth.context_processors.auth. 这个上下文处理器负责在每个请求中包含用户对象。

于 2013-06-26T06:48:01.143 回答
2

这取决于您设置的内容。

所以,最好使用

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

'django.core.context_processors.request'实际上,如果您附加到TEMPLATE_CONTEXT_PROCESSORS列表中,则不需要定义此类变量settings.py

然后你可以在模板中访问变量 {{ request.user.username }} 如果你在render使用views.py

于 2013-06-26T06:49:43.927 回答
0

request.user 指的是实际的用户模型实例。

request.user.FIELDNAME 将允许您访问用户模型的所有字段

于 2013-06-26T06:24:40.227 回答