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

Posted

技术标签:

【中文标题】如何在 Django 应用程序中获取有关登录用户的信息?【英文标题】:How can I get information about the logged-in user in a Django application? 【发布时间】:2021-10-29 13:49:06 【问题描述】:

我想要做的是从登录用户那里获取用户信息,并将附加信息存储在数据库(models.py)中。 所以在views.py中:

def registerView(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login_url')
        
        else:
            form = UserCreationForm()
            return render(request, 'main/register.html','form':form)

这里如何获取用户信息

【问题讨论】:

任何帮助表示赞赏 请添加细节解决方法 所以在视图中 .py def registerView(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login_url') else: form = UserCreationForm() return render(request, 'main/register.html','form':form)这里如何获取用户信息 在您的问题中添加这些内容 【参考方案1】:

在 django 中有几种方法可以从经过身份验证的用户那里获取信息

1) 在视图中

您可以像这样使用 request.user

def test_user(request):
    if request.user.is_authenticated:
        # Do some stuff with the user = request.user
        my_user = request.user
        my_user.email = 'demo_user@yopmail.com'
        my_user.save()
    else:
        # The user is not authenticated
        # You can't do anything i guess
    return render(request, 'template/logged_in_user.html')

2) 在模板中

<!-- Show something to the authenticated user -->
% if user.is_authenticated %
<h1> Hi  user.name  </h1>
% else %
<!-- Show something to the guess user -->
<h1> Hi Guess ! </h1>
% endif %

【讨论】:

以上是关于如何在 Django 应用程序中获取有关登录用户的信息?的主要内容,如果未能解决你的问题,请参考以下文章