Django logout view shows a blank page and does not log out a user

30 views Asked by At

I faced an issue with my logout view. I created a custom CBV that inherits from the default Django LogoutView. The interesting fact is that it works perfectly fine with the FBV. When I associate the /logout/ URL with the CBV there appears only a blank page and does not log out the signed user. I have also created a template that is visualized without any problems with the FBV. Here you can see my views:

from django.shortcuts import redirect, render
from django.contrib.auth import views as auth_views, get_user_model, logout
from django.urls import reverse_lazy
from django.views import generic as views
from accounts.forms import MyUserCreationForm

UserModel = get_user_model()


# Create your views here.
class MyUserRegisterView(views.CreateView):
    template_name = "user-register.html"
    form_class = MyUserCreationForm
    success_url = reverse_lazy("home page")


class MyUserLoginView(auth_views.LoginView):
    template_name = "user-login.html"


class MyUserLogoutView(auth_views.LogoutView):
    template_name = "user-logout.html"


def logout_view(request):
    if request.method == "POST":
        logout(request)
        return redirect("home page")
    return render(request, "user-logout.html")

Here are my urls:

from django.urls import path
from accounts import views


urlpatterns = (
    path("register/", views.MyUserRegisterView.as_view(), name="register"),
    path("login/", views.MyUserLoginView.as_view(), name="login"),
    path("logout/", views.MyUserLogoutView.as_view(), name="logout"),
)

I have also defined LOGOUT_REDIRECT_URL = reverse_lazy("home page") in settings.py

here is also my template which is working fine with the FBV and does its job:

{% if request.user.is_authenticated %}

<h1>Are you sure you want to logout, {{ request.user }}?</h1>

<form action="{% url 'logout' %}" method="post">    

    {% csrf_token %}

    <button>Logout</button>

</form>

{% else %}

<h1>No user logged in</h1>

{% endif %}

The URL to hit the logout is: http://127.0.0.1:8000/accounts/logout/

Thank you in advance good people!

0

There are 0 answers