Search code examples
python-3.xdjangodjango-views

Django built-in LogoutView is always 'GET'


First stuck with "Method Not Allowed (GET): /logout/", found answer, changed template so method is 'POST'(tried 'post'), but now despite it I'm still getting "Method Not Allowed (GET): /logout/", since method is still 'GET'. Same happens when LogoutView.as_view() is empty.

urls.py

from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from users import views as user_views


urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', user_views.register, name='register'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('', include('blog.urls')),
]

full html file(/users/templates/users/logout.html)

<form method="POST" >
    {% csrf_token %}
    <button type="submit">logout</button>
</form>

command prompt when I'm going to http://localhost:8000/logout/

Method Not Allowed (GET): /logout/
Method Not Allowed: /logout/
[04/Feb/2024 17:30:07] "GET /logout/ HTTP/1.1" 405 0
Method Not Allowed (GET): /logout/
Method Not Allowed: /logout/
[04/Feb/2024 17:30:08] "GET /logout/ HTTP/1.1" 405 0

Can I change method to 'POST' instead of 'GET' with built-in LogoutView?

Tried to find answers for "Method Not Allowed (GET): /logout/", but all I got was to change form method to 'POST', but I'm still getting 'GET' method.


Solution

  • The logout view has no template. You put this in another template where the user can logout.

    For example if you have home template, you can put it there:

    <!-- on a template where you want to add a logout button -->
    <form method="POST" action="{% url 'logout' %}">
        {% csrf_token %}
        <button type="submit">logout</button>
    </form>