Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name. I am unable to redirect a url page.

I have created a user login and register. Now I want to redirect the home page to the login page when the user clicks “logout”.

I am not sure why but I keep having problems whenever I redirect.

This is my views.py

from django.contrib.auth import forms
from django.contrib.auth.models import User
from django.contrib.messages.api import error
from django.shortcuts import render, redirect, HttpResponse
from django.views.generic import View, TemplateView
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from .forms import CreateUserForm

def registerPage(request):
    form = CreateUserForm()
    
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            form.save()
            user = form.cleaned_data.get('username')
            messages.success(request, 'Account was successfully created for '+ user)
            # return redirect('login')
        else:
            messages.error(request, 'Unsuccessful! ')  
   
    context = {'form':form}  
    return render(request, 'home/register.html', context)

def loginPage(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(request, username=username, password=password)     
        
        if user is not None:
            login(request, user)
            return redirect('/')
        else:
            messages.error(request, 'Incorrect username or password')
			
    context = {}
    return render(request, 'home/login.html', context)

def logoutUser(request):
    logout(request)
    return redirect('login')

def home(request):
    return render(request, 'home/home.html')

My app urls.py

from django.urls import path
from django.conf.urls import url
from . import views

app_name = 'user'
urlpatterns = [
    path('register/', views.registerPage, name="register"),
    path('login/', views.loginPage, name="login"),
    path('logout/', views.logoutUser, name="logout"),
    path('', views.home, name="home"),
    url(r'^feedback/$', views.feedback, name="feedback"),
]

My project urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('sentiment/', include('sentiment.urls')),
    path('', include('user.urls')),
]

My home.html

<!DOCTYPE html>
<html lang="en">
{% load static %}
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Home page</title>
    </head>
    <body>
  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

          <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav mr-auto">
              <li class="nav-item active">
                  <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
              </li>
              <li class="nav-item">
                <a class="nav-link"  href="/sentiment/type">Input Text</a>
            </li>
              <li class="nav-item">
                  <a class="nav-link"  href="/sentiment/import">Import Tweets</a>
              </li>
              <li class="nav-item">
                  <a class="nav-link" href="/feedback">Feedback</a>
              </li>
          </ul>
      </div>
      <span ><a  class="hello-msg" href="{% url 'logout' %}">Logout</a></span>
  </nav>
<h1>Welcome To Homepage</h1>

Can anyone help me with this? I have searched everywhere but still couldn’t solve this issue. Let me know if you need anything else.

What exactly is throwing this error? Can you post the actual and complete traceback message from your console when this occurs? What code is trying to redirect to “logout” that is failing?

i want to redirect logout to the login page.

This is the code that’s not working in the html file.

 <span ><a  class="hello-msg" href="{% url 'logout' %}">Logout</a></span>

This is a screenshot of the error.

My console

I want to redirect to the login page after logout

(Side Note: For future reference, please do not post images of code or tracebacks. Copy/paste the text of the messages into your posting, between lines of three backtick - ` characters. (A line of ```, then the traceback, then another line of ```.) Images are really tough to work with here.)

Ok, first step is understanding the error message.

Right underneath the yellow block it says:

Error during template rendering.

This has nothing to do with your redirect. This is happening when Django is trying to render your home page. This is only an issue in your template.

Yes, you’ve identified the location of the problem in your template - it can’t convert that line into html because:

‘logout’ is not a valid view function or pattern name.

And this is caused by:

You specified an app_name in the urls.py file, which means that when you try to reverse that url, the url name is now “app_name”:“url_name”, or in this specific case:

<span ><a class="hello-msg" href="{% url 'user:logout' %}">Logout</a></span>

2 Likes

First of all thanks for the side note. This is my first time posting on a community forum so I didn’t really know much. I’m also very new to django and python.

I see what you mean about the app_name:url_name

I changed that part in html page
<span ><a class="hello-msg" href="{% url 'user:logout' %}">Logout</a></span>

as well as my views.py

def logoutUser(request):
    logout(request)
    return redirect('user:login')

and it worked!

Thank you so much for taking the time to identify and respond to my problem. I really appreciate it :slight_smile: