Django URLs NoReverseMatch - python

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).

Related

DRF does not reverse Django url pattern: NoReverseMatch

There is a complex app (not possible to just paste the code). Going to try to explain.
Django
There is a urls.py file from the native Django app. The urlpatterns defines and register its urls. The ^foo/ defines a group of related urls and the foonamepsace.
urlpatterns = patterns('',
...
url(r'^foo/', include('foo.urls', namespace='foonamespace')),
...
Now there is a method generate_report which does some logic inside and then uses render_to_string to return the HTML:
def generate_report(..):
...
return render_to_string('foo/foo_report.html', args)
Everything works inside the app, the url get reversed successfully.
Django Rest Framework (DRF)
Now there is a DRF implementation and one of its resources is supposed to return a report in a binary format.
class PDFReportViewSet(APIView):
renderer_classes = (BinaryFileRenderer, )
def get(..):
...
pdf = generate_report() # <-- fails with NoReverseMatch
...
return response
Problem
The ViewSet calls the generate_report, however one gets an error when trying to parse the HTML:
NoReverseMatch: foonamespace' is not a registered namespace
Question
Any clues why DRF cannot reverse the namespcae/url from the the core of Django app? How to make sure DRF can reverse a namespace from the core urls.py urlpattern?
Added
After investigation, inside the foo_report.html any usage of the url, for example {% url 'foonamespace:123' %} or {% url 'barnamespace:123' %} produces the error - only if ran from the DRF (running the same page using native Django works fine).
URLS
foo.urls.py
from django.conf.urls import patterns, url
from foo.views import (FooListView, FooDetailView...)
urlpatterns = patterns('',
url(r'^$', FooListView.as_view(), name='foo_list'),
url(r'^(?P<pk>\d+)/$', FooDetailView.as_view(), name='foo_details'),
Important note. The app is served at some.domain.com/, while the REST is served from some.domain.com/rest. So may be this way /rest just don't include anything because it is a parent of the root (which includes the foo.urls.py)
I was managed to resolve my issue with the help from #dirkgroten. It was difficult to see the problem without looking at the source code.
Solution
Updated the routers.py file:
urlpatterns = router.urls
urlpatterns += patterns('',
url(r'^foo/', include('foo.urls', namespace='foonamespace')),
)
Explanation
Basically, the app was serve from the root url / while the rest was served from /rest. The DRF router simply didn't include any of the root routes. Adding them manually like it is shown in solution resolved the problem and made foonamespace visible for all DRF elements.

Django: - NoReverseMatch error

I'm following the djangoforgirls.org tutorial on making my first django site. I'm trying the stage "extending your template" to make a link to an article within my website that uses the general template.
I keep get thrown the error: "NoReverseMatch at /, Reverse for 'post_detail' with arguments '()' and keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P\d+)/$']"
Some variable and file names may seem strange, the use of the website was music sampling but I used the tutorial's names for things in case that was what was wrong.
My urls.py for entire project:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('sample.urls')),
]
My urls.py for the specific app (sample):
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
My views.py for the app:
from django.utils import timezone
from .models import AudioSample
from django.shortcuts import render, get_object_or_404
def post_list(request):
samples = AudioSample.objects.order_by('length')
return render(request, 'blog/post_list.html', {'samples': samples})
def post_detail(request, pk):
post = get_object_or_404(AudioSample, pk=pk)
return render(request, 'blog/post.html', {'post': post})
And the line of code from the base template that's the link to another page in the website:
How to sample
I saw another person that asked this question with a similar project here and got it fixed but I dont understand the answer enough to make the change to mine (I dont understand what the namespace is).
If you have more than one urls.py, namespace can tell django how to handle the request. So in normally, namespace is the APP name.
In your project urls.py, try replacing r'' with r'^'. The former matches all urls, while the latter matches the start of the string.

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.

Django: getting NoReverseMatch at / error

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})

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