django if user.is_authenticated not working but login user

Issue

my problem is that the login operation is done correctly and the session is set up correctly, but user.is_authenticated does not work.
The point is that it works when I log in through the admin, but not like this, what can I do to fix it?

session set true image

my code :

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>

Solution

I am writing this for friends who have this problem

The solution to this issue is that the user must be is_active equal to True to perform the login operation, otherwise the section

request.user.is_authenticated

Otherwise it does not work and does not enter the user

Answered By – Reza Shakeri

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published