【问题标题】:Django user authentication not working on every subpageDjango 用户身份验证不适用于每个子页面
【发布时间】:2020-09-29 17:04:45
【问题描述】:

我在 Django 中的用户身份验证存在奇怪(而且可能很简单)的问题。 我在 base.html 文件中添加了这段代码:

{% if user.is_authenticated %}
    <p>{{user.get_username}} is logged in</p>
    <a href="{% url 'logout' %}">logout</a>
{% else %}
    <p>You are not logged in!</p>
    <a href="{% url 'login' %}">login</a></a>
{% endif %}

然后我将这一行添加到其他所有模板中:

{% extends "base.html" %}

看起来不错,因为每个子页面都显示这行代码,不幸的是,有时在用户通过身份验证时显示代码,有时在他未通过身份验证时显示代码。例如,当我在两个子页面之间切换时,一旦我获得用户登录信息是登录后,在第二个网页上,我得到了我未登录的信息,当我回到第一个子页面时,我再次通过身份验证...

我怎么能改变它?可能是什么问题?

我对登录的看法:

def login_user(request):
    login_user = {}
    login_user.update(csrf(request))
    return render_to_response('login.html', login)


def auth_view(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)

    if user is not None and user.is_active:
        auth.login(request, user)
        return redirect('loggedin')
    else:
        return HttpResponseRedirect('invalidlogin')


def logged_in(request):
    return render_to_response('loggedin.html',
                              {'user': request.user})

还有我的“登录”网址:

path('login', views.login, name='login'),
path('authorized', views.auth_view, name='authorized'),
path('loggedout', views.loggedout, name='loggedout'),
path('loggedin', views.loggedin, name='loggedin'),
path('invalidlogin', views.invalidlogin, name='invalidlogin'),

【问题讨论】:

  • 你最好尝试使用像@require_user 这样的装饰器,并将其应用到视图中。
  • 感谢您的回复@ilyas-jumadurdyew,但是我如何使用这个装饰器来处理每个子页面?

标签: python django authentication django-templates


【解决方案1】:
from django.contrib.auth.decorators import login_required

@login_required(login_url='/accounts/login/')
def my_view(request):

https://docs.djangoproject.com/en/3.1/topics/auth/default/#django.contrib.auth.decorators.login_required

【讨论】:

  • 谢谢,我在链接中读到了它。据我了解,这个装饰器适用于我想在我的子页面上使用的视图。但是,如果我想在每个子页面上都进行此身份验证怎么办?例如在主页上,当我没有任何视图时,我只想显示一些基本的用户名。
猜你喜欢
  • 2016-07-03
  • 2021-08-23
  • 1970-01-01
  • 2014-08-16
  • 2019-06-13
  • 1970-01-01
  • 2016-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多