Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass multiple url parameters in django

Tags:

python

django

I have 2 links in my html templates. First link pass only 1 parameter to URL and second link pass 2 parameters. Like this:

<a href="/products/{{categ_name}}">{{categ_name}}</a>
<a href="/products/{{categ_name}}/{{subcateg_name}}">{{subcateg_name}}</a>

Now when i click on link with 1 parameter it works fine. I get the parameter value in my django view.
But When i click on link with two parameters i only get the first parameter. I get None in the value of second parameter.

My urls.py:

urlpatterns = patterns('',
            url(r'^products/(?P<categ_name>\w+)/', views.products, name='products_category'),
            url(r'^products/(?P<categ_name>\w+)/(?P<subcateg_name>\w+)/', views.products, name='products_subcategory'),
            url(r'^logout/',views.logoutView, name='logout'),)

My views.py:

def products(request, categ_name=None, subcateg_name=None):
    print categ_name, subcateg_name
    ...

How to get the value of second parametre?

like image 904
Manish Gupta Avatar asked Nov 18 '15 16:11

Manish Gupta


1 Answers

Change your urls to:

urlpatterns = patterns('',
            url(r'^products/(?P<categ_name>\w+)/$', views.products, name='products_category'),
            url(r'^products/(?P<categ_name>\w+)/(?P<subcateg_name>\w+)/$', views.products, name='products_subcategory'),
            url(r'^logout/',views.logoutView, name='logout'),)

Then, you avoid your 2-parameter url being matched by the first 1-parameter pattern. The $ special character means end of string.

like image 182
Maciek Avatar answered Oct 01 '22 02:10

Maciek