AdrianCR
AdrianCR

Reputation: 23

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: <a href="{% url 'polls.views.student_detail' id=student.id %}">{{student.stduent_name}}</a></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

Upvotes: 1

Views: 7344

Answers (3)

Juan D. G&#243;mez
Juan D. G&#243;mez

Reputation: 499

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: <a href="{% url 'student_detail' student.id %}">{{student.stduent_name}}</a></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.

Upvotes: 1

AzMoo
AzMoo

Reputation: 506

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.

Upvotes: 1

Frank T
Frank T

Reputation: 9066

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.

Upvotes: 4

Related Questions