简体   繁体   English

如何在django模板中打印有关用户(谁被登录)的信息?

[英]How I can print informations about user (who is logged) in django template?

I have template like this : 我有这样的模板:

<html>
<body>
You are logged as John Kowalski
</body>
</html>

I would like show first_name and last_name of user but this doesn't work: 我想显示用户的first_name和last_name但这不起作用:

<html>
<body>
You are logged as {{ request.user.first_name }} {{ request.user.last_name }}
</body>
</html>

How can I get user object in template? 如何在模板中获取用户对象?

You need to do a few things: 你需要做一些事情:

First, add the following to your settings: 首先,将以下内容添加到您的设置中:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request', 
)

(You can add other context processors, but this is the relevant one.) (您可以添加其他上下文处理器,但这是相关的。)

Second, in your views: 第二,在你的观点中:

Import this: 导入此:

from django.template import RequestContext

And in your views, return your templates like this: 在您的视图中,返回您的模板,如下所示:

return render_to_response('something.html', context_instance=RequestContext(request))

You can now access the request object in your template. 您现在可以访问模板中的request对象。

Learn more here: https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext 在此处了解更多信息: https//docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext

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

相关问题 如何仅在Django中打印当前登录的用户数据? - How can I only print the the current logged in user data in Django? 如何在 Django 中获取特定用户的信息(我想获取现在已登录的特定用户的约会历史记录) - how to get information for specific user in Django ( i wanted to get Appointment history for specific user who is now logged in ) 如何在 Django 中获取用户(当前登录的用户)的帖子? - How to get the posts of a user (who is currently logged in) in django? 如何在表单 django 中添加登录的用户名 - How can I add the logged in user's name in form django 如何在 Django 中获取登录用户的用户名? - How can I get the username of the logged-in user in Django? 用户登录django时如何更改标题? - How can I change header when user is logged in django? 如何在登录用户的视图中保存 django Model 表单 - How can I save a django Model Form in views for the logged in user 仅当登录用户是创建 object 的用户时,如何使编辑和取消链接出现? Django - How do I make the edit and cancel link appear only if its the logged in user is the one who created the object? Django 每次用户在 Django 中登录和注销时,如何登录? - How can I log every time a user has logged in and logged out in Django? 如何获取当前用户的JWT信息? - How can I get current user's JWT informations?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM