Search code examples
pythondjangourlurlconf

Django: variable parameters in URLconf


I've been looking for this question and couldn't find any, sorry if it's duplicated.

I'm building some kind of ecommerce site, similar to ebay. The problem i have arise when i'm trying to browse through "categories" and "filters". For example. You can browse the "Monitor" category. That will show you lots of monitors, and some filters (exactly the same as ebay) to apply them. So, you go to "monitors", then you have filters like:

  • Type: LCD - LED - CRT
  • Brand: ViewSonic - LG - Samsung
  • Max Resolution: 800x600 - 1024x768

And those filters will be appended to the URL, following with the example, when you browse monitors the URL could be something like:

store.com/monitors

If you apply the "Type" filter:

store.com/monitors/LCD

"Brand":

store.com/monitors/LCD/LG

"Max Resolution":

store.com/monitors/LCD/LG/1024x768

So, summarizing, the URL structure would be something like:

/category/filter1/filter2/filter3

I can't figure out how to do it really. The problem is that filters can be variable. I think in the view will need to use **kwargs but i'm not really sure.

Do you have any idea how to capture that kind of parameters?

Thanks a lot!


Solution

  • Ben, I hope this will help you

    urls.py

    from catalog.views import catalog_products_view
    
    urlpatterns = patterns(
        '',
        url(r'^(?P<category>[\w-]+)/$', catalog_products_view, name="catalog_products_view"),
        url(r'^(?P<category>[\w-]+)/(?P<filter1>[\w-]+)/$', catalog_products_view, name="catalog_products_view"),
        url(r'^(?P<category>[\w-]+)/(?P<filter1>[\w-]+)/(?P<filter2>[\w-]+)/$', catalog_products_view, name="catalog_products_view"),
        url(r'^(?P<category>[\w-]+)/(?P<filter1>[\w-]+)/(?P<filter2>[\w-]+)/(?P<filter3>[\w-]+)/$', catalog_products_view, name="catalog_products_view"),
    )
    

    view.py

    def catalog_products_view(request, category, filter1=None, filter2=None, filter3=None):
        # some code here
    

    or

    def catalog_products_view(request, category, **kwargs):
        filter1 = kwargs['filter1']
        filter2 = kwargs['filter2']
        ....
        filterN = kwargs['filterN']
        # some code here