I am fairly new to Django and I use Django 4.2. I am building a website and I have run into this error. I have created my login function like this
def loginUsers(request):
context = {}
if request.method == 'POST':
email = request.POST['email']
upass = request.POST['password']
user = authenticate(request, email=email, password=upass)
if user is not None:
login(request, user)
messages.success(request, 'Login successful')
time.sleep(2)
return redirect(reverse('index'))
else:
messages.error(request, 'Invalid user')
return redirect(reverse('login'))
return render(request, 'auth_pages/login.html', context)
But my logout function is not in this contact app views.py. It is in my index app views.py because the logout button in my template is in the navbar. Here it is:
def loadIndexPage(request):
context = {}
print(request.user.is_authenticated)
return render(request, 'pages/index.html', context)
def logoutUser(request):
if request.method == 'POST':
logout(request)
messages.success(request, 'You are logged out')
return redirect(reverse('login'))
The problem
The problem is that the logout function is not logging out the user, it instead, is creating a csrftokenmiddleware in the browser search bar and when I print the
request.user.is_authenticated it prints false. In the template:
{% if request.user.is_authenticated %}
<p>Hey there user</p>
{% else %}
<p>Not working</p>
{% endif %}
This is not working. It is only showing Not working.
I have tried to add a @login_required to the index function, but it kept redirecting to a page that I never created or added in the urls.py of the project.
I have gone through the documentation and did everything as stated but yet the issues persist.
I have tried to print out the request.user.is_authenticated and it is still printing false, even though the user is authenticated in the login function.
I checked the database and the column, is_authenticated is still FALSE.
I have two questions:
- Is anything wrong with my code?
- Should I have set the column
is_authenticatedto True?
>Solution :
You likely made a GET request, the form should be:
<form method="POST" action="{% url 'logout' %}">
{% csrf_token %}
<button type="submit">logout</button>
</form>
Likely the method="POST" is lacking, so it makes a GET request. Logging in/out should be done through a POST request, since this changes the state.
I checked the database and the column, is_authenticated is still FALSE.
Normally the User model does not have a column named is_authenticated. This is not a database column, this is simply true for all Users. If the user is not logged in, request.User will return the AnonymousUser object, which has is_authenticated returning False.