Reputation: 239
This is my first django project with login/out. On login the user is successfully redirected to his dashboard, however when I click logout nothing happens. Any ideas how can I fix this issue?
view:
def logout(request):
#logout(request)
if request.method == 'POST':
auth.logout(request)
messages.success(request, 'You are now logged out')
return redirect('login')
html:
{% if user.is_authenticated %}
<div id = 'dashboard' class="the-dashboard">
<div class="prof">
<p ><span class = 'fntmk'>Welcome</span> {{ user.username }}</p>
<img src = "{% static 'images/profile-trans.jpg' %}">
</div>
<div class="the-panel">
<form action = "{% url 'logout' %}" method = "POST">
{% csrf_token %}
<a class = 'fntmk'><i class="far fa-user-circle size"></i> Profil</a>
<a href="{% url 'logout' %}" class = 'logout fntmk prob' alt='exit'><span class="material-icons">logout</span><span class = 'odjavi'>Logout</span></a>
</div></form>
</div>
{% else %}
<div class="the-login">
<form action = "{% url 'login' %}" method = "POST">
{% csrf_token %}
<input type = 'text' id = 'username' class = 'username-field' placeholder = 'username' required>
<input type = 'password' id = 'password' placeholder = 'password' required>
<a href= "{% url 'login' %}"> <button class = 'btn-login'>Login</button></a>
</form>
<a href = "{% url 'register' %}" class = 'register fntmk'>New User?</a>
</div>
{% endif %}
urls>
path('register/',register, name = 'register'),
path('accounts/dashboard/',login, name = 'login'),
path('',logout, name = 'logout'),
Upvotes: 0
Views: 87
Reputation: 2006
The problem is located in this line:
<a href="{% url 'logout' %}" class = 'logout fntmk prob' alt='exit'><span class="material-icons">logout</span><span class = 'odjavi'>Logout</span></a>
When clicking here you're sending a GET request to your logout view.
So you can either modify your view in order to accept GET requests or a better solution is to remove this link so it actually becomes a button that submit your form.
<input type="submit" value="Logout">
Edit:
I see you're doing the same for the login. Always use a <input type='submit' value='...'>
or <button type='submit'> ... </button>
to submit a form.
Upvotes: 2