如何在 Django 中获取登录用户的用户名? [英] How can I get the username of the logged-in user in Django?

查看:98
本文介绍了如何在 Django 中获取登录用户的用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Django 应用程序中获取有关登录用户的信息?

How can I get information about the logged-in user in a Django application?

例如:

我需要知道登录用户的用户名才能说出谁发布了评论:

I need to know the username of the logged-in user to say who posted a Review:

<form id='formulario' method='POST' action=''>
    <h2>Publica tu tuit, {{ usuario.username.title }} </h2>
    {% csrf_token %}
    {{formulario.as_p}}
    <p><input type='submit' value='Confirmar' /></p>
</form>

usuario.username.title 中,我获得了用户名,但在模板中,我需要从视图中获得该信息.

In usuario.username.title I get the username, but in the template, I need to get that information from the view.

推荐答案

您可以使用请求对象来查找已登录的用户

You can use the request object to find the logged in user

def my_view(request):
    username = None
    if request.user.is_authenticated():
        username = request.user.username

根据https://docs.djangoproject.com/en/2.0/releases/1.10/

在 Django 2.0 版本中,语法已更改为

In version Django 2.0 the syntax has changed to

request.user.is_authenticated

这篇关于如何在 Django 中获取登录用户的用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆