Django - Reverse for '' not found. '' is not a valid view function or pattern name [duplicate]
Asked Answered
A

27

95

I'm working on my project for a course and I'm totally stuck right now. I'm creating a website to sell products through paypal and the paypal return/cancel pages are not rendering properly. I've followed the examples in my lessons and checked the code a hundred times but obviously there is something I'm missing.

I'm getting an error when I go to products, click buy now, login to paypal and then either cancel the purchase or buy the product and return to merchant's page. paypal_return.html and paypal_cancel.html are 2 templates saved under templates/paypal/

Can anybody see what I'm missing?

Here you can see the full code https://github.com/IreneG5/spss_online

Traceback

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/paypal-cancel/

Django Version: 1.11.4
Python Version: 2.7.12

Installed Applications:

['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django_forms_bootstrap',
 'paypal.standard.ipn',
 'home',
 'accounts',
 'paypal_store',
 'products']

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 C:\Users\irene\Documents\Full-Stack-Developer\Stream3\Project\spss_online\templates\base.html, error at line 10
   Reverse for '' not found. '' is not a valid view function or pattern name.   1 : {% load staticfiles %}
   2 : <!DOCTYPE html>
   3 : <html lang="en">
   4 : <head>
   5 :     <meta charset="UTF-8">
   6 :     <title>Buy SPSS Online</title>
   7 :     <meta name="viewport" content="width=device-width, initial-scale=1.0">
   8 :     <meta name="description" content="">
   9 :     <meta name="author" content="">
   10 :     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/cerulean/bootstrap.min.css">
   11 :     <link rel="stylesheet" href="{% static 'css/style.css' %}">
   12 : 
   13 : 
   14 : </head>
   15 : <body>
   16 : <div class="container">
   17 :     <div class='container-fluid'>
   18 :         <nav id="menu" class="navbar navbar-inverse">
   19 :             <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
   20 :                 <span class="icon-bar"></span>

Traceback:

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\irene\Documents\Full-Stack-Developer\Stream3\Project\spss_online\paypal_store\views.py" in paypal_cancel
  15.     return render(request, 'paypal/paypal_cancel.html', args)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\loader.py" in render_to_string
  68.     return template.render(context, request)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\base.py" in render
  207.                     return self._render(context)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\loader_tags.py" in render
  177.             return compiled_parent._render(context)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\loader_tags.py" in render
  72.                 result = block.nodelist.render(context)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\base.py" in render
  990.                 bit = node.render_annotated(context)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\base.py" in render_annotated
  957.             return self.render(context)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\template\defaulttags.py" in render
  458.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\urls\base.py" in reverse
  91.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "C:\Users\irene\virtualenv\spss_online_env\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
  497.         raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /paypal-cancel/
Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name.
Avicenna answered 16/8, 2017 at 22:36 Comment(1)
You have to use with app name eg. {% url 'core:home' %} here core is the name of the app and home the view name.Mazel
E
99

When you use the url tag you should use quotes for string literals, for example:

{% url 'products' %}

At the moment product is treated like a variable and evaluates to '' in the error message.

Ellipticity answered 18/8, 2017 at 23:22 Comment(2)
That was it. I added the quotes in the template and the name='products' in urls.py and it works now. Thanks Alasdair!Avicenna
This may also be the correct answer for the question of "why does a legacy django form that submits to the same page no longer work after upgrading django". I make this comment so Google can help others find the answer.Hanshaw
T
53
  1. The syntax for specifying url is {% url namespace:url_name %}. So, check if you have added the app_name in urls.py.
  2. In my case, I had misspelled the url_name. The urls.py had the following content path('<int:question_id>/', views.detail, name='question_detail') whereas the index.html file had the following entry <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>. Notice the incorrect name.
Turmoil answered 7/1, 2019 at 14:23 Comment(4)
In my case, I added the app_name to my urls.py and then missed to include the "namespace:" prefix. So thank you for bringing this to my attention!Flawed
This is so far one of the best answers I found. No one seems to mention {% url 'namespace:url_name' %} - People respond with {%url 'url_name' %}Altamirano
Dude thanks for pointing that out - incidentally, I feel there may be a mistake in the Django official tutorial? THey also omit the namespace prefix...Morose
It is also worth mentioning that there is no space between namespace and url_name. In my case, space was the errorPhares
W
29

I was receiving the same error when not specifying the app name before pattern name. In my case:

app-name : Blog

pattern-name : post-delete

reverse_lazy('Blog:post-delete') worked.

Witham answered 30/11, 2019 at 15:44 Comment(2)
Where do you add reverse_lazy('Blog:post-delete')?Presignify
@DerekPK E.g, while assigning to success_url or in get_success_url method.Witham
S
11

Add store name to template like {% url 'app_name:url_name' %}

App_name = store

In urls.py, path('search', views.searched, name="searched"),

<form action="{% url 'store:searched' %}" method="POST">

Stockinet answered 4/10, 2020 at 15:19 Comment(0)
I
9

You can use one of these.

If you did not (app_name) This is the solution

in urls.py

urlpatterns = [
    path('', dashboard.as_view(), name='dashboard'),
]

in template.html

<a href="{% url 'dashboard' %}"></a>

If you did (app_name) This is the solution

in urls.py

app_name = 'Blog'
urlpatterns = [
    path('', dashboard.as_view(), name='dashboard'),
]

in template.html

<a href="{% url 'Blog:dashboard' %}"></a>
Iinden answered 8/11, 2021 at 12:13 Comment(1)
man, idk how many post did I read on how reverse works, and this post of yours is literally help me finally understanding it. THANK YOU!!!!Sumo
H
8

Specify app_name in the urls.py file of an app and use this app_name along with the string literal view name of the url in templates:

syntax --> {% url 'app_name:urlname' %}

app_name = "demo".   # right above url patterns in app
url_patterns = [
('login/', views.login, name = 'login')
]

<a href="{% url 'demo:login' %}".  # Use this in templatep

Note: use the app_name right above the url_patterns in urls.py file.

Hardworking answered 23/5, 2021 at 23:11 Comment(0)
I
6

Fix urlpatterns in urls.py file

For example, my app name is "simulator",

My URL pattern for login and logout looks like

urlpatterns = [
    ...
    ...
    url(r'^login/$', simulator.views.login_view, name="login"),
    url(r'^logout/$', simulator.views.logout_view, name="logout"),
    ...
    ...

]
Insulator answered 8/5, 2019 at 2:46 Comment(0)
N
4

In my case, what I did was a mistake in the url tag in the respective template. So, in my url tag I had something like

{% url 'polls:details' question.id %}

while in the views, I had written something like:

def details(request, question_id): code here

So, the first thing you might wanna check is whether things are spelled as they shoould be. The next thing then you can do is as the people above have suggested.

Newspaper answered 22/1, 2020 at 4:47 Comment(0)
C
4

In my case, this error occurred because I forgot to add app_name along with url_name. Below is my app urls.py

    app_name = "wikis"
    urlpatterns = [
        path("", views.index, name="index"),
        path("wiki/<str:name>", views.get_page, name="get_page"),
       ]

Below is my function's return statement where I forgot to put app_name in reverse URL

    return HttpResponseRedirect(reverse("get_page", kwargs={'name':title}))

Correct code would be

    return HttpResponseRedirect(reverse("wikis:get_page", kwargs={'name':title}))
Contrabassoon answered 18/3, 2021 at 5:7 Comment(1)
This answer is very close to how I fixed. I was using a different name in the path function so it was not matching. But it worked after I used the correct path name in the Reverse function without the app name. So from above explanation this worked for me <code> return HttpResponseRedirect(reverse("get_page", kwargs={'name':title}))</code>Overstretch
S
2

*Always make sure when you use HttpResponseRedirect and reverse, the name you specify inside reverse is the same name you gave to your path inside urls.py

Thats the problem i had and i found out through trial and error*

Shela answered 19/4, 2021 at 20:7 Comment(0)
A
2

I too faced the same issue while testing, for me it was caused when url was empty in html

<td><a href="{% url '' test.id %}"><i class="fa fa-times" aria-hidden="true"></i></a></td>

So after I changed it by putting the url name:

<td><a href="{% url 'task_delete' test.id %}"><i class="fa fa-times" aria-hidden="true"></i></a></td>
Aplite answered 20/11, 2021 at 7:22 Comment(0)
C
1

In my case, I don't put namespace_name in the url tag ex: {% url 'url_name or pattern name' %}. you have to specify the namespace_name like: {% url 'namespace_name:url_name or pattern name' %}.

Explanation: In project urls.py path('', include('blog.urls',namespace='blog')), and in app's urls.py you have to specify the app_name. like app_name = 'blog'. namespace_name is the app_name.

Clarkin answered 3/7, 2020 at 16:2 Comment(0)
P
1

You can also get this error if you forget to add the app url in the project url

Example: Project/urls.py

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

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

and you have a store/urls.py

so if you have html code in store/templates/store and you want to add in app/templates/app an a tag with the url to an html code in store/templates/store

You would have to include the store/urls.py in Project/urls.py

Project/urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('app.urls')),
    path('', include('store.urls')),
]
Presignify answered 31/7, 2021 at 4:12 Comment(0)
D
1

I've been reading this for past two days to compare mine to see why it didn't work. it turns out a space between ":" matters: mine had a space between ":" and "index":

<a href="{% url 'namespace: index' %}">Home</a>

thought this worth mentioning in case someone like me scratching their heads in the future: No space around the colon, or anywhere before or after "namespace" and "index"

Deedeeann answered 27/3, 2022 at 7:49 Comment(0)
K
1

The simple solution is

 path('detail/', views.detail, name="This_is_the_solution"),

you have to give the name value to the url,

<a href="{% url 'This_is_the_solution' %}"></a>
Kirschner answered 1/6, 2022 at 18:22 Comment(0)
B
1

It is like that you have written wrong pattern of url in template file. Such that you write

instead {% url 'claim:cashless_opd_send_otp' %}
Bernard answered 3/4, 2023 at 4:37 Comment(1)
{% url 'cashless_opd/send_otp' %} to {% url 'view:route_name' %} example: {% url 'claim:cashless_opd_send_otp' %}Bernard
C
0

If you dont define name in the path field, usually the error will come. e.g.: path('crud/',ABC.as_view(),name="crud")

Cottar answered 27/12, 2019 at 5:35 Comment(1)
This is not the answer. Edit it in order to the question or write it in comments.Dockyard
S
0

Give the same name in urls.py

 path('detail/<int:id>', views.detail, name="detail"),
Spheroid answered 16/3, 2020 at 16:51 Comment(1)
Can you give a bit more detail about your suggestion? Why will it help?Hognut
H
0

In my case, this error occurred due to a mismatched url name. e.g,

<form action="{% url 'test-view' %}" method="POST">

urls.py

path("test/", views.test, name='test-view'),
Humerus answered 31/12, 2020 at 18:56 Comment(0)
S
0

*Always make sure when you use HttpResponseRedirect and reverse, the name you specify inside reverse is the same name you gave to your path inside urls.py

'return HttpResponseRedirect(reverse("index")) path("index/",views.index,name="index")'

Thats the problem i had and i found out through trial and error*

Shela answered 19/4, 2021 at 20:10 Comment(0)
M
0

I have faced the same problem. The mistake was I declared same name for multiple urlpatterns.

 path('file', views.sender, name='sender'),

Here the name should be different and unique for different url.

Marchak answered 4/7, 2021 at 5:30 Comment(0)
T
0

Let's say in your template home.html you are having a form that does a POST request, like:

<form id="form_id" action = "{% url 'home' %}" method = "post" > .. </form>

In your urls.py you have

url(r'^$', views.home_view, name='home')

in your view, you can check the passed data from template like this.

def home_view(request): print(request.POST)

it is important in urls.py to declare a name='home' and on your action part on the form to include this url action = "{% url 'home' %}"

Tattler answered 18/10, 2021 at 11:50 Comment(0)
S
0

In Some cases: You should not forgot to load the home page or base page by using eg: {%extends "app_name/web_page.html"%>

Seabrooke answered 8/7, 2022 at 17:10 Comment(0)
B
0

Thanks for all the solutions shared by various folks. I had the same issue when I was trying to use url template of Django Below is the scenario mentioned below:

We have an app with name base and inside that we have base/urls.py file. Below are the entries we have in base/urls.py file

urlpatterns = [
    path("", views.homepage, name='home'),
    path("room/<str:pk>/", views.room, name='room')
]

When I was trying to access these url pattern as below in our template, we were getting the error

<div>
    <p>
        <a href="{% url 'room' room.id %}">{{ room.id }}</a>
        - {{ room.name }}
    </p>
</div>

The issue occurs due to the way we have defined the url template. To resolve this issue, I simply need to prefix the app name as below

<div>
    <p>
        <a href="{% url 'base:room' room.id %}">{{ room.id }}</a>
        - {{ room.name }}
    </p>
</div>
Biodynamics answered 9/2 at 7:58 Comment(0)
H
-1

The common error that I have found is when you forget to define your URL in yourapp/urls.py.

Hagan answered 5/5, 2019 at 11:10 Comment(0)
C
-1

On line 10 there's a space between s and t. It should be one word: stylesheet.

Canonry answered 11/9, 2019 at 8:29 Comment(1)
Can you explain that further? Why should that additional space trigger the given error?Parous
C
-1

appname=demo url=/student

href="{% url 'demo:student' %}"

Make Sure you should not have space before or after : (colon)

Claver answered 15/4, 2021 at 9:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.