9

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?

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Side note: It's also possible to simply re-order the URL patterns so that the more specific one is listed first. Django processes URLs on first-match-wins basis. Explicitly adding the anchor is probably cleaner, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.