django 如果 user.is_authenticated 不工作但登录用户

django if user.is_authenticated not working but login user

我的问题是登录操作正确完成并且会话设置正确,但是 user.is_authenticated 不起作用。 关键是当我通过管理员登录时它可以工作,但不是这样,我该如何解决?

我的代码:

views.py

class LoginView(View):
    def get(self, request):
        login_form = LoginForm()
        context = {
            'login_form': login_form
        }
        return render(request, 'account/login.html', context)

    def post(self, request: HttpRequest):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user_email = login_form.cleaned_data.get('email')
            user_password = login_form.cleaned_data.get('password')
            user: User = User.objects.filter(email__iexact=user_email).first()
            if user is not None:
                check_password = user.check_password(user_password)
                if check_password:
                    login(request, user)
                    return redirect('home')
                else:
                    login_form.add_error('password', 'password is not correct !')
            else:
                login_form.add_error('email', 'email dose not exists !')
        context = {
            'login_form': login_form
        }
        return render(request, 'account/login.html', context)

header_component.html

<div class="navbar__list">
    <ul class="navbar__links">
        {% for link in links %}
            <li class="navbar__link"><a href="{{ link.url }}">{{ link.name|capfirst }}</a></li>
        {% endfor %}
        {% if user.is_authenticated %}
            <li class="navbar__link"><a href="#">welcome</a></li>
            <li class="navbar__link"><a href="{% url 'logout' %}">Log out</a></li>
        {% else %}
            <li class="navbar__link"><a href="{% url 'login' %}">Login</a></li>
            <li class="navbar__link"><a href="{% url 'register' %}">Register</a></li>
        {% endif %}
    </ul>
</div>

{% if user.is_authenticated %} 已弃用。

改用这个:

{% if request.user.is_authenticated %}
    # Do something for authenticated users.
    ...
{% else %}
    # Do something for anonymous users.
    ...

根据documentation

Django uses sessions and middleware to hook the authentication system into request objects. These provide a request.user attribute on every request which represents the current user. If the current user has not logged in, this attribute will be set to an instance of AnonymousUser, otherwise it will be an instance of User. You can tell them apart with is_authenticated as shown above.

编辑:添加文档说明。

写给遇到这个问题的朋友

这个问题的解决方法是用户必须is_active等于True才能执行登录操作,否则第

request.user.is_authenticated

否则不起作用,不进入用户