Desh__
Desh__

Reputation: 899

Django url template tag with variable

In my urls.py I have something along these lines

 # Dont use repeating patterns when only the end changes.
 url(r'^products/', include(patterns('foo.apps.bar.views',
    url(r'^$', 'product_family', name='products'),
    url(r'^(?P<page>[\w-]+)$', 'product_single'),
    ...
 ))),

Which would equate to:

www.demo.com/products/ - take you to a page where we see all products www.demo.com/products/alpha - take you to the alpha product page - if alpha does not exist it redirects to the products page

I can link to these pages via the specified 'name' in urls.py

<a href="{% url 'products' %}">Products</a>

How can I do the same but supply it with a variable to take me to product_single?

<a href="{% url 'products/{{ products.slug }}' %}">Products</a>

I know I could just write out the link without the url tag but was curious if there was syntax to use it like the a href above?

Upvotes: 2

Views: 7843

Answers (1)

rockingskier
rockingskier

Reputation: 9346

Give your single product url a name.

url(
    r'^products/',
    include(
        patterns('foo.apps.bar.views',
            url(r'^$', 'product_family', name='products'),
            url(r'^(?P<page>[\w-]+)$', name='product_single'),
        )
    )
),

Pass the slug to the newly named url.

<a href="{% url 'product_single' products.slug %}">Products</a>
{# OR #}
<a href="{% url 'product_single' page=products.slug %}">Products</a>

Upvotes: 5

Related Questions