When I go to localhost:121/logout I get The view accounts.views.logout didn't return an HttpResponse object. It returned None instead.
Should I modify my code, to deal with this, or is this not an issue? My logout is working fine. Do I have to list logout in my urls.py?
views.py
def logout(request):
if request.method == "POST":
auth.logout(request)
return redirect('login')
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('register/', views.register, name='register'),
path('logout', views.logout, name='logout'),
path('', views.login, name='login'),
]
profile.html
<ul>
<li>
<a class="dropdown-item" href="javascript:{document.getElementById('logout').submit()}">Logout</a>
</li>
<form id="logout" action="{% url 'logout' %}" method="POST">
{% csrf_token %}
<input type="hidden">
</form>
</ul>
It really depends on what you want your application to do. What do you want to happen when you navigate to /logout
? If you want to provide your users with a way of logging out just by navigating there, then you can just deal with the GET and POST requests together. (As suggested by @Beste) e.g:
def logout(request):
auth.logout(request)
return redirect('login')
This has the additional advantage that you can logout from anywhere on the site just by using a hyperlink to this URL.
If you don't want this to happen, I would suggest raising a 405 (method not allowed), e.g:
from django.http import HttpResponse
def logout(request):
if request.method == "POST":
auth.logout(request)
return redirect('login')
return HttpResponse(status_code=405)
And yes, whatever you do you will need to list it in your urls.py
somewhere. Or you could even use a HttpResponseNotAllowed
(see here)