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.
Related
I have an issue where I try to go to my redirect page and get a NoReverseMatch when though the URL is there? Any idea how to fix this?
I have checked that the "schema" url works and it correctly supplies the openapi schema, but the other page simply can't understand the url.
URLS:
urlpatterns = [
path("schema/", SpectacularAPIView.as_view(), name="schema"),
# Optional UI:
path("docs/", SpectacularSwaggerView.as_view(url_name="schema"), name="swagger-ui"),
]
Errors:
For reverse url pathing, you have to use {% url api:schema %}. It's specified as namespace next to include('api.urls') or inside app urls, just above urlpatterns - like app_name = "api".
Django is unable to load my template because "NoReverseMatch at /books/outlines/20
"
This issue lies within a link in the template:
New Blank Outline
Here is my outlines/urls.py
from django.urls import path
from .views import Dashboard
from . import views as outline_views
urlpatterns = [
path('<int:pk>/', outlines_views.outline, name='url-outline')
path('blank/<int:storyPk>', outline_views.newBlankOutline, name='url-blankOutline'),
path('test/', outline_views.testView, name = 'test')
]
urlpatterns += staticfiles_urlpatterns()
Here is the testView:
def testView(request):
return render(request, 'outlines/test.html')
Here is the outline view:
def outline(request, pk):
context = {
'storyPk': pk
}
return render(request, 'outlines/outline.html', context)
The django error tells me:
NoReverseMatch at /books/outlines/20
Reverse for 'test' not found. 'test' is not a valid view function or pattern name.
The weird thing is, if I change the url name in the template to a url name from another app's urls.py file, it renders the template no problem. Any idea why it can't find the url?
New Blank Outline
how about try this
I'm trying to use pass a parameter to a URL in Django, but I keep getting this error:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/%7B%25%20url%20review%20review_id%3D3%20%25%7D
Using the URLconf defined in soundclinic.urls, Django tried these URL patterns, in this order:
[name='index']
login/ [name='login']
register/ [name='register']
create_user [name='create_user']
<int:review_id>/review/ [name='review']
admin/
main/
The current path, {% url review review_id=3 %}, didn't match any of these.
The link I am follow has a tag like above: {% url review review_id=3 %}
I'm not sure what I'm not including right, as it looks like I'm writing out the url tag correctly and urls.py seems to be configured correcely as well.
Manually entering in the URL calls the correct views.py function, so it only has to do with my urls.py file.
As kszl already said, you must use " ' " around your URL name.
{% url 'review' review_id=3 %}
It supposes you have a URL in some url.py that has the name "review".
It seems to be the case though since we can see
<int:review_id>/review/ [name='review']
in your log message.
Error Message:*<br/><br/>
NoReverseMatch at /
Reverse for 'get_travel_details' with arguments '()' and keyword arguments '{u'origin': u'bus_terminals.Bus_Terminal_Id', u'destination': u'bus_terminals.Bus_Terminal_Id', u'travel_date': u'travel_date'}' not found. 1 pattern(s) tried: ['(?P< travel_date >\\w+)/travel_date/(?P< origin >\\w+)/origin/(?P< destination >\\w+)/destination']
I am trying to pass values to the url's parameters through the form action, this is what my form tag looks in my html file:
<form method = "POST" action ="{% url 'brats:get_travel_details' travel_date='travel_date' origin='bus_terminals.Bus_Terminal_Id' destination='bus_terminals.Bus_Terminal_Id' %}" id = "find_travel_form">
And then my urls.py at the project folder:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^master/', admin.site.urls),
url(r'^', include('bus_reservation_system.urls')),
url(r'^(?P<travel_date>\w+)/travel_date/(?P<origin>\w+)/origin/(?P<destination>\w+)/destination$', include('bus_reservation_system.urls')),
]
And then my urls.py at the app folder:
from django.conf.urls import include, url
from . import views
app_name = "brats"
urlpatterns = [
url(r'^', views.index, name = "index"),
url(r'^(?P<travel_date>\w+)/travel_date/(?P<origin>\w+)/origin/(?P<destination>\w+)/destination', views.get_travel_details, name = "get_travel_details"),
]
The parameters: travel_date, origin, destination should be a string value to be passed.
And this is my views.py looks:
def get_travel_details(request, travel_date, origin, destination):
errors = []
if request.method == 'POST':
if not request.POST.get('travel_date', ''):
errors.append('Please determine your date of travel.\n')
if not request.POST.get('origin', ''):
errors.append('Please determine your point of origin.\n')
if not request.POST.get('destination', ''):
errors.append('Please determine your point of destination.\n')
if not errors:
all_bus = bus.objects.all()
elif errors:
travel_schedules = travel_schedule.objects.all()
bus_terminals = bus_terminal.objects.all()
bus_types = bus_type.objects.all()
data = {'travel_schedules': travel_schedules, 'bus_terminals': bus_terminals, 'errors': errors}
return render(request, 'pages/index.html', data)
Your url is still passing in strings, that include a ., which isn't included in your regex. I doubt that you actually want the dot and have a string id so just remove the quotes..
So change
{% url 'brats:get_travel_details' travel_date='travel_date' origin='bus_terminals.Bus_Terminal_Id' destination='bus_terminals.Bus_Terminal_Id' %}
to
{% url 'brats:get_travel_details' travel_date='travel_date' origin=bus_terminals.Bus_Terminal_Id destination=bus_terminals.Bus_Terminal_Id %}
And make sure that Bus_Terminal_Id's don't have any non-word characters
tl;dr
To fix the error, remove the following line from your main urls:
url(r'^(?P<travel_date>\w+)/travel_date/(?P<origin>\w+)/origin/(?P<destination>\w+)/destination$', include('bus_reservation_system.urls')),
Explanation
You have two urls pointing to the same app. So, everytime you write {% url 'brats:get_travel_details' ...}, Django resolves it to the last registered url which, in your case is this:
url(r'^(?P<travel_date>\w+)/travel_date/(?P<origin>\w+)/origin/(?P<destination>\w+)/destination$', include('bus_reservation_system.urls')),
Which finally gets resolved to this:
'(?P<travel_date>\w+)/travel_date/(?P<origin>\w+)/origin/(?P<destination>\w+)/destination/(?P<travel_date>\w+)/travel_date/(?P<origin>\w+)/origin/(?P<destination>\w+)/destination'
As you can see, the final resolved url requires 6 parameters but you're only passing it 3.
Which is why you're getting the error.
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 %}