Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Build URLs from template with integer param, the primary key

Tags:

python

django

I have this link in a template:

<a href="{% url show_item item.id %}">Item 1</a>

and this url in the urls.py

url(r'item/(?P<id>)/$', show_item, name="page_item")

however, this error occurs:

Reverse for 'show_item' with arguments '(63L,)' and keyword arguments '{}' not found.

I looked at this question:

how to get python to not append L to longs or ignore in django template

but it did not help.

Is there another way to use the primary key, which is an integer, in constructing URLs in templates?

like image 548
yretuta Avatar asked Jun 22 '12 01:06

yretuta


People also ask

How do I pass parameters via URL in Django?

Django URL pass parameter to view You can pass a URL parameter from the URL to a view using a path converter. Then “products” will be the URL endpoint. A path converter defines which type of data will a parameter store. You can compare path converters with data types.

How do I create a URL in Django?

Here's an example URLconf and view: # URLconf from django.urls import path from . import views urlpatterns = [ path('blog/', views.page), path('blog/page<int:num>/', views.page), ] # View (in blog/views.py) def page(request, num=1): # Output the appropriate page of blog entries, according to num. ...

How do I reference a URL in Django?

Django offers a way to name urls so it's easy to reference them in view methods and templates. The most basic technique to name Django urls is to add the name attribute to url definitions in urls.py .

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.


2 Answers

The URL name doesn't match. Change the template to be:

<a href="{% url page_item item.id %}">Item 1</a>
like image 200
Ned Batchelder Avatar answered Sep 28 '22 14:09

Ned Batchelder


It should be page_item not show_item in template.

like image 35
iMom0 Avatar answered Sep 28 '22 14:09

iMom0