I am working on a project where an organization will login and then logout if they want. But somehow the logout functionality is not working. No redirect is happening and the user is not able to logout.
# urls.py
urlpatterns = [
path('logout',views.user_logout,name = 'logout')
]
# views.py
def user_logout(request):
if request.method == "POST":
logout(request)
return HttpResponseRedirect('login')
# template:
<a href="#" onClick="document.getElementById('logoutform').submit()" class="btn">
Logout</a>
<form id="logoutform" method="POST" action="{% url 'logout' %}">
{% csrf_token %}
<input type="hidden">
</form>
The page just reloads and no redirect happens.
I think you've made this more complicated than it needs to be. Django comes with a LogoutView
, and it allows logouts with GET requests. You could use that logout view, or change your own to:
from django.shortcuts import redirect
def user_logout(request):
logout(request)
return HttpResponseRedirect('login') # assumes you have a URL pattern with name='login'.
Note that HttpResponseRedirect('login')
will redirect to the relative URL 'login'
, so you might end up at /logout/login
. You should either use the absolute URL (e.g. HttpResponseRedirect('/login/')
), reverse the URL (e.g. return HttpResponseRedirect(reverse('login'))
, or use the redirect
shortcut which takes care of reversing for you.
Once you have changed the logout view, you can remove the form and simply link to the logout page.
<a href="{% url 'logout' %}" onClick="document.getElementById('logoutform').submit()" class="btn">Logout</a>