Raul kumar
Raul kumar

Reputation: 31

Django logout template not working even with POST

This is my logged_out.html

{% extends 'base.html' %}

{% block title %}
    Logout
{% endblock %}

{% block content %}
<form action="{% url 'login' %}", method="POST">
    {% csrf_token %}
    <button type="submit">Logout</button>
</form>
{% endblock %}

This is my urls.py file


urlpatterns = [
    ...
    path('accounts/', include("django.contrib.auth.urls")),
    path('accounts/logout/', auth_views.LogoutView.as_view(template_name='logged_out.html'), name='logout'),
]

view.py

@require_POST
def user_logout(request):
    logout(request)
    return render(request, "registration/logged_out.html", {})

I've followed the docs to make the /logout a POST and I still get 405 error saying it's a GET request. How do I solve this?

Upvotes: 0

Views: 46

Answers (1)

elkhayyat
elkhayyat

Reputation: 56

The issue that you are sending the POST request to the login form here:

<form action="{% url 'login' %}", method="POST">

it should be something like this: logged_out.html

{% extends 'base.html' %}

{% block title %}
    Logout
{% endblock %}

{% block content %}
<form action="{% url 'logout' %}", method="POST">
    {% csrf_token %}
    <button type="submit">Logout</button>
</form>
{% endblock %}

and the views.py to be:

def user_logout(request):
    if request.POST:
        logout(request)
        return redirect('login')
    return render(request, "registration/logged_out.html", {})

in this case if when the user accessing the logout page using GET request it show him Logout button when he clicks on it, it will logout him then redirect the user to the login page

Upvotes: 0

Related Questions