Reverse for 'login' not found. 'login' is not a valid view function or pattern name.

i got this error while using django authentication views:

Error during template rendering

In template /../../templates/base.html , error at line 0

Reverse for ‘login’ not found. ‘login’ is not a valid view function or pattern name.

2 	{% load static %}
3 	<!DOCTYPE html>
4 	<html>
5 	
6 	<head>
7 	  <title>{% block title %}{% endblock %}</title>
8 	  <link href="{% static "css/blog.css" %}" rel="stylesheet">
9 	</head>
10 

My Login Form Code

<div class="login-form">
  <form action="{% url 'login' %}" method="post">
    {{ form.as_p }}
    {% csrf_token %}
    <input type="hidden" name="next" value="{{ next }}" />
    <p><input type="submit" value="Log-in"></p>
  </form>
</div>

My urls.py code

from django.contrib.auth import views as auth_views
path('login/', auth_views.LoginView.as_view(), name='login'),

Don’t understand the point where i’m missing.

In urls.py, is that path() in the urlpatterns assignment?
‘’’

from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(), name='login'),
]

Are there any other patterns in urls.py?

-Jorge

1 Like

yes it is in urlpatterns.

urlpatterns = [
    path('', views.PostList, name='PostList'),
    path('tag/<slug:tag_slug>/',views.PostList,name = 'PostListByTag'),
    # path('',views.PostListView.as_view(), name='PostList'),
    path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.PostDetail,name='PostDetail'),
    path('<int:post_id>/share/',views.PostShare, name='PostShare'),
    path('feed/',LatestPostsFeed(),name='PostFeed'),
    path('search/', views.PostSearch,name='PostSearch'),
    path('login/', auth_views.LoginView.as_view(), name='login'),
]

May be you can get something from Traceback Message:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/blog/login/

Django Version: 3.0.6
Python Version: 3.8.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'django.contrib.sitemaps',
 'django.contrib.postgres',
 'blog.apps.BlogConfig',
 'taggit']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template /home/aman/mysite/mysite/blog/templates/base.html, error at line 0
   Reverse for 'login' not found. 'login' is not a valid view function or pattern name.
   1 : {% load blog_tags %}
   2 : {% load static %}
   3 : <!DOCTYPE html>
   4 : <html>
   5 : 
   6 : <head>
   7 :   <title>{% block title %}{% endblock %}</title>
   8 :   <link href="{% static "css/blog.css" %}" rel="stylesheet">
   9 : </head>
   10 : 


Traceback (most recent call last):
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/core/handlers/base.py", line 145, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/core/handlers/base.py", line 143, in _get_response
    response = response.render()
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/response.py", line 105, in render
    self.content = self.rendered_content
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/response.py", line 83, in rendered_content
    return template.render(context, self._request)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/base.py", line 171, in render
    return self._render(context)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/base.py", line 936, in render
    bit = node.render_annotated(context)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated
    return self.render(context)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/template/defaulttags.py", line 443, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/urls/base.py", line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "/home/aman/blog/blog/lib/python3.8/site-packages/django/urls/resolvers.py", line 677, in _reverse_with_prefix
    raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /blog/login/
Exception Value: Reverse for 'login' not found. 'login' is not a valid view function or pattern name.

Is urls.py the one in the project folder, or is it in /blogs? If it’s in the app, can we please see your root urls.py?

it’s the blog app folder not the root folder.
root folder code is:

from django.contrib import admin
from django.urls import path, include
from django.contrib.sitemaps.views import sitemap

from blog.sitemaps import PostSitemap

sitemaps = {
    'posts': PostSitemap,
}

urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls', namespace='blog')),
    path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
]

It seems that you’re including the blog/urls.py in the project with a namespace. In that case, the reverse would be namespace:view name, or in your case, blog:login. Try that in your template inside the url tag and see if that works.

-Jorge

16 Likes

Ok so got that fixed thanks a lot. just a newbie problem. but the learning was good. i forgot about the namespace. :grinning: :grinning:

1 Like

The first time I had that happen, it took me HOURS to figure it out. Glad I could help!

-Jorge

7 Likes

can you please send a screenshot of your fixed code? im having the same issue

Can you put your template code here. Main problem is there only. The reverse would be namespace:view in template rendering.

Thank you! This is the answer I was looking for aswell,

I was searching for this!! you’ve solved my issue!! thank you so much!!

this is my project urls.py

 urlpatterns = [
    path('', include('blog.urls', namespace='blog:blog-home')),

    path('admin/', admin.site.urls),

    path('register/', user_views.register, name='register'),

    path('profile/', user_views.profile, name='profile'),

        

    path('djrichtextfield/', include('djrichtextfield.urls')),

    path('ckeditor/', include('ckeditor_uploader.urls')),

    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('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'),

    path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'),

    path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'),

    path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

and here is the blog app urls.py

urlpatterns = [

    path('', PostListView.as_view(), name='blog-home'),

    path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),

    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),

    path('post/new/', PostCreateView.as_view(), name='post-create'),

    path('about', views.about, name='blog-about'),

    path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),

    path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),

    path('like/', like_post, name='like-post'),

    path('serialized/', post_serialized_view, name='serialized_view'),

]

i’m still getting this error…
Reverse for 'blog-home' not found. 'blog-home' is not a valid view function or pattern name.
Any kind of help will be highly appreciated.

In the project urls.py, you have this:

urlpatterns = [
    path('', include('blog.urls', namespace='blog:blog-home'))

(snipped the remainder for brevity’s sake)

The namespace is added to the front of the reverse. I don’t know if one is allowed to have a colon in the namespace, as I’ve never tried that. I would write this as so:

urlpatterns = [
    path('', include('blog.urls', namespace='blog')),

Which makes the reverse for the ‘’ path as blog:blog-home. What does your template where this error comes up look like?

-Jorge

This is the correct answer. I thought it was optional to add the namespacing to a url tag especially because I had only one application. Thanks

the same mistake question,info is…

|Request URL:|http://127.0.0.1:8000/store/cart/|
|Django Version:|2.1.8|
|Exception Type:|NoReverseMatch|
|Exception Value:|Reverse for ‘store’ not found. ‘store’ is not a valid view function or pattern name.|

django.urls.exceptions.NoReverseMatch: Reverse for ‘store’ not found. ‘store’ is not a valid view function or pattern name.
[09/Dec/2020 12:54:04] “GET /store/cart/ HTTP/1.1” 500 157901

django-admin startproject [projectname]
::: setting>urls.py
urlpatterns = [
path(‘store/’, include(‘store.urls’, namespace=‘store’)),
path(‘posts/’, include(‘posts.urls’, namespace=‘posts’)),
path(’’, include(‘home.urls’)),
path(‘admin/’, admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

python manage.py startapp store
:::store/url.py

app_name = ‘store’

urlpatterns = [
path(‘store/’, views.store, name=‘store’),
path(‘cart/’, views.cart, name=‘cart’),
path(‘checkout/’, views.checkout, name=‘checkout’),
]


########################### views.py ############################
def store(request):
data = cartData(request)

cartItems = data['cartItems']
order = data['order']
items = data['items']

products = Product.objects.all()
context = {'products':products, 'cartItems':cartItems}
return render(request, 'store/store.html', context)

def cart(request):
data = cartData(request)

cartItems = data['cartItems']
order = data['order']
items = data['items']

context = {'items':items, 'order':order, 'cartItems':cartItems}
return render(request, 'store/cart.html', context)

Can someone help? What should I do?
Or … Or what information should I give less? PLZ…

Somewhere in a view or template you’re attempting to reverse a url named ‘store’. You can try ‘store:store’. If that doesn’t work, we’ll need to see the view or template that is generating this error.

you say mean is —> return render(request, {{store:store}}, context)???
or —> return render(request, “store:store”, context)???

I have tried both of these methods, but this problem will evolve in the future, but there are no errors in my program, and running out of the dict makes me a little puzzled QWQ

Attach the link to the result after the operation: https://paste.ubuntu.com/p/TJKWBBwSTc/

plz help … SOS

How to write
return render(request,‘store/cart.html’, context) ???

1.return render(request,‘store: store’, context)
or
2.return render(request, {{store: store}}, context)
I have tried both of these methods, but this problem will evolve in the future, but there are no errors in my program, and running out of the dict makes me a little puzzled QWQ

Attach follow-up results:

sorry for bothering,

  1. Add app_name =‘store’ in urls.py ->

Then in my views.py,
def store(request):
data = cartData(request)

cartItems = data['cartItems']
order = data['order']
items = data['items']

products = Product.objects.all()
context = {'products': products,'cartItems': cartItems}

—-> return render(request, {{store: store}}, context)
—-> return render(request, {{store: cart}}, context)
—-> return render(request, {{store: checkout}}, context)

{{store: store}} After this is used,
This message is produced Exception Value: unhashable type:‘dict’

Excuse me, is this {{store: store}} wrong? Someone uses something like this? Or there are keywords that allow me to query django. I really don’t see these things in the django data. QWQ also rarely sees people using this way. Can they give me similar knowledge? ?

  1. If I “do not” do this {{store: store}}{{store: cart}}{{store: checkout}}, enter the shopping cart http://127.0.0.1:8000/store/cart/ will produce This error occurred: Reverse for’store’‘cart’‘checkout’ not found.‘store’ is not a valid view function or pattern name.

Then very unexpectedly, there is no error in def store, def cart(request):, the problem is the dict in the cart

third,

Picture two and three are the same,
Is it a symbol problem in the () [] {} def cart() program?
def cart(request):
data = cartData(request)

cartItems = data['cartItems']
order = data['order']
items = data['items']

context = {'items': items,'order': order,'cartItems': cartItems}
return render(request, {{store: cart}}, context)

{{store: cart}} -> It is impossible to change django to [[ ]] (()) like this R… strange QWQ

Thank you in advance~~~

CAN visit views.pt.py

from django.shortcuts import render
from django.http import JsonResponse
import json
import datetime
from .models import *
from .utils import cookieCart, cartData, guestOrder

def store(request):
data = cartData(request)

cartItems = data['cartItems']
order = data['order']
items = data['items']

products = Product.objects.all()
context = {'products': products,'cartItems': cartItems}
return render(request, {{store:store}}, context)

def cart(request):
data = cartData(request)

cartItems = data['cartItems']
order = data['order']
items = data['items']

context = {'items': items,'order': order,'cartItems': cartItems}
return render(request, {{store: cart}}, context)

def checkout(request):
data = cartData(request) # The amount of cookiesData is changed to data change -> cookieData = cookieCart(request)
cartItems = data[‘cartItems’] # cartItems = cookieData[‘cartItems’]
order = data[‘order’] # order = cookieData[‘order’]
items = data[‘items’] # items = cookieData[‘items’]

context = {'items': items,'order': order,'cartItems': cartItems}
return render(request, {{store: checkout}}, context)

THX …