Django: getting NoReverseMatch at / error - python

There are a lot of similar issues on SO and i went through most of them, but still unable to resolve my problem.
I am getting the following error:
Reverse for 'category_view' with arguments '()' and keyword arguments
'{'pk': 'dynamic-programming'}' not found. 0 pattern(s) tried: []
NoReverseMatch at /articles/
Here is my settings from urls.py file:
url(r'^category/(?P<pk>[\w-]+)/$', views.CategoryDetailView.as_view(), name='category_view')
And, this is my definition of get_absolute_url() from model;
def get_absolute_url(self):
return reverse('category_view', kwargs={'pk': self.slug})
And the caller where I am getting this error is from index.html:
<li>{{ category.name }}</li>
I am sure that I am missing something very obvious, but not able to figure it out for past few hours. :(
Content from project's urls.py:
url(r'^articles/$', include('blog.urls', namespace="blog")),
url(r'^admin/', include(admin.site.urls)),

I suspect that you forgot to include the urls.py from your app into the project's urls.py.
UPDATE: if you used the namespace parameter of the include then you have to specify this namespace in the reverse() call:
def get_absolute_url(self):
return reverse('blog:category_view', kwargs={'pk': self.slug})

Related

Passing context to view from template: NoReverseMatch error

Trying to pass context from template to my view (whether ad=True or False). Here's how I've tried to do it:
urls.py
url(r'^$', home, name='bv'),
url(r'^q/', search, name='search'),
url(r'^post/', include('post.urls')),
post.urls
url(r'^$', views.post, name='post'),
url(r'^edit/(?P<id>\d+)/', views.edit, name='edit'),
url(r'^delete/(?P<id>\d+)/', views.delete, name='delete'),
template
Proceed
post.views
def post(request, ad=False):
...
the ad='True' in the template should pass onto the views and change the default ad=False to ad=True. Instead, I get this error message:
NoReverseMatch at /advertise/
Reverse for 'post' with arguments '()' and keyword arguments '{'ad': 'True'}'
not found. 1 pattern(s) tried: ['post/$']
Any idea what the problem is?
change route:
url(r'^(?P<ad>\w+)$', views.post, name='post'),
and better answer:
url(r'^(?P<ad>(True|False))$', views.post, name='post'),

DJango - NoReverseMatch Error

That is the exception value:
Reverse for '' with arguments '()' and keyword arguments '{'id': 1}' not found. 0 pattern(s) tried: []
index.html
<p>Estudiante: {{student.stduent_name}}</p>
The link should go to a route like this "127.0.0.1:8000/polls/1/". The route works fine out of the link.
views.py
def student_detail(request, id):
student = get_object_or_404(Student, id=id)
return render(request, 'polls/student_detail.html', {'student': student})
urls.py
urlpatterns = [
url(r'^$', views.index),
url(r'^polls/(?P<id>[0-9]+)/', views.student_detail),
]
Images:
Error details
Route tree
The first argument to the url template tag is the "url name". You need to specify a name when you define the route, something like:
url(r'^polls/(?P<id>[0-9]+)/', views.student_detail, name='student-detail'),
and then update your template to use it like:
{% url 'student-detail' id=student.id %}
See the documentation on the url template and url names.
The template code in the exception is different to the template code you've pasted in your question. The exception indicates your template tag looks like:
{% url polls.views.student_detail id=student.id %}
Note the missing quotes which is consistent with the exception. Without the quotes django is attempting to resolve polls.views.student_detail as a variable instead of passing it as a string to the template tag. Since it can't resolve you're passing a blank string to your template tag.
You are invoking an url by name but there's no such named url in the urls.py file.
your urlpatterns should be:
urlpatterns = [
url(r'^$', views.index),
url(r'^polls/(?P<id>[0-9]+)/', views.student_detail, name='student_detail'),
]
And then in your template:
<p>Estudiante: {{student.stduent_name}}</p>
notice that you don't need to explicitly pass the parameter name, Django transforms each parameter separated by space in the respective parameter specified in the url regex pattern.

NoReverseMatch using reverse and url with args

I am trying to use the reverse function in django with no luck. I already tried to change the args and use all combinations of long, int, string, unicode-string, etc, with the same error.
Help, please? Thanks.
Error I am getting:
Exception Type: NoReverseMatch at /ajax/data-request
Exception Value: Reverse for 'views.watch' with arguments '(1, 1, 'aaa')' and keyword arguments '{}' not found. 0 pattern(s) tried: []
urls.py:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.index, name='index'),
url(r'^options/', views.options, name='options'),
url(r'^recuperar-contrasena/', views.recover_password, name='recover_password'),
url(r'^ajax/login', views.login_ajax, name='login_ajax'),
url(r'^ajax/data-request', views.data_request, name='data_request'),
url(r'^peliculas-populares', views.movies_popular, name='movies_popular'),
url(r'^peliculas-todas', views.movies_all, name='movies_all'),
url(r'^watch/(?P<is_movie>\d+)-(?P<id>\d+)/(?P<name>.*)$', views.watch, name='watch')
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Reverse function:
'watch-url': reverse('views.watch', None, [(is_movie), (movie.id), (slugify(movie.title))])
{% url %} that works in my template:
{% url "watch" 1 movie.id movie.title|slugify %}
The reverse() call is incorrect, should be:
reverse('watch', None, [(is_movie), (movie.id), (slugify(movie.title))]

Django URLs NoReverseMatch

I've been trying to figure this out, but can't seem to catch my error.
In my Django 1.6 project I have two apps: hold and control
Project urls.py
url(r'^control/$', include('control.urls')),
App control/urls.py
url(r'^$', views.index, name='control_home'),
#this doesn't work
url(r'^invite/$', views.control_invite, name='control_invite'),
Control views.py
def index(request):
return render(request, 'control_index.html')
def control_invite(request):
return render(request, 'control_invite.html')
Template control_index.html
<li class="active">Control</li>
<li>Invitations</li>
Error
Reverse for 'control_invite' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['control/$invite/$']
I get the same error in the shell. Not sure what I'm missing...
You have a $ sign at the end of your main urls.py which means the pattern should end at control/ and not allow any more sub-urls. Change it to this:
url(r'^control/', include('control.urls')),
Project urls.py should be:
url(r'^control/', include('control.urls')),
There is no need for $ (it means nothing comes after that).

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

Caught an exception while rendering:
Reverse for 'products.views.'filter_by_led' with arguments '()' and
keyword arguments '{}' not found.
I was able to successfully import products.views.filter_by_led from the shell and it worked so the path should be correct.
Here is the urls.py:
(r'^led-tv/$', filter_by_led ),
This is where the error is being generated:
href="{% url products.views.filter_by_led %}">
Which I can't understand because this works fine from the same file:
{% url products.views.lcd_screen_size screen_size=50 %}
Here is the function definition:
def filter_by_led(request):
I don't understand why Django would think that the function would not be able to find the Reverse for that function.
I deleted all the *.pyc files and restarted Apache.
What am I doing wrong?
There are 3 things I can think of off the top of my head:
Just used named urls, it's more robust and maintainable anyway
Try using django.core.urlresolvers.reverse at the command line for a (possibly) better error
>>> from django.core.urlresolvers import reverse
>>> reverse('products.views.filter_by_led')
Check to see if you have more than one url that points to that view
Shell calls to reverse (as mentioned above) are very good to debug these problems, but there are two critical conditions:
you must supply arguments that matches whatever arguments the view needs,
these arguments must match regexp patterns.
Yes, it's logical. Yes, it's also confusing because reverse will only throw the exception and won't give you any further hints.
An example of URL pattern:
url(r'^cookies/(?P<hostname>[^/]+)/(?P<url_id>\d+)/$', 'register_site.views.show_cookies', name='show_cookies'),
And then what happens in shell:
>>> from register_site.views import show_cookies
>>> reverse(show_cookies)
NoReverseMatch: Reverse for 'register_site.views.show_cookies' with arguments '()' and keyword arguments '{}' not found.
It doesn't work because I supplied no arguments.
>>> reverse('show_cookies', kwargs={'url_id':123,'hostname': 'aaa'})
'/cookies/aaa/123'
Now it worked, but...
>>> reverse('show_cookies', kwargs={'url_id':'x','hostname': 'www.dupa.com'})
NoReverseMatch: Reverse for 'show_cookies' with arguments '()' and keyword arguments '{'url_id': 'x', 'hostname': 'www.dupa.com'}' not found.
Now it didn't work because url_id didn't match the regexp (expected numeric, supplied string).
You can use reverse with both positional arguments and keyword arguments. The syntax is:
reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None)
As it comes to the url template tag, there's funny thing about it. Django documentation gives example of using quoted view name:
{% url 'news.views.year_archive' yearvar %}
So I used it in a similar way in my HTML template:
{% url 'show_cookies' hostname=u.hostname url_id=u.pk %}
But this didn't work for me. But the exception message gave me a hint of what could be wrong - note the double single quotes around view name:
Reverse for ''show_cookies'' with arguments...
It started to work when I removed the quotes:
{% url show_cookies hostname=u.hostname url_id=u.pk %}
And this is confusing.
You need single quotes around the view name
{% url 'viewname' %}
instead of
{% url viewname %}
I had a similar problem and the solution was in the right use of the '$' (end-of-string) character:
My main url.py looked like this (notice the $ character):
urlpatterns = [
url(r'^admin/', include(admin.site.urls )),
url(r'^$', include('card_purchase.urls' )),
]
and my url.py for my card_purchases app said:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^purchase/$', views.purchase_detail, name='purchase')
]
I used the '$' twice. So a simple change worked:
urlpatterns = [
url(r'^admin/', include(admin.site.urls )),
url(r'^cp/', include('card_purchase.urls' )),
]
Notice the change in the second url! My url.py for my card_purchases app looks like this:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^purchase/$', views.purchase_detail, name='purchase')
]
Apart from this, I can confirm that quotes around named urls are crucial!
In case it helps someone, I had a similar issue and the error was because of two reasons:
Not using the app's namespace before the url name
{% url 'app_name:url_name' %}
Missing single quotes around the url name (as pointed out here by Charlie)
I don't think you need the trailing slash in the URL entry. Ie, put this instead:
(r'^led-tv$', filter_by_led ),
This is assuming you have trailing slashes enabled, which is the default.
{% url 'polls:create' poll.id %}

Categories

Resources