Django: variable parameters in URLconf

I was looking for this question and could not find it, sorry if it is duplicated.

I am creating an e-commerce site similar to ebay. The problem occurs when I try to view the "categories" and "filters". For instance. You can view the "Monitor" category. This will show you a lot of monitors and some filters (exactly the same as ebay) to apply them. So, you go to the "monitors", then you have filters like:

  • Type: LCD - LED - CRT
  • Brand Name: ViewSonic - LG - Samsung
  • Maximum resolution: 800x600 - 1024x768

And these filters will be added to the URL, following the example when you are viewing monitors, the URL might look something like this:

store.com/monitors 

If you apply the Type filter:

 store.com/monitors/LCD 

"Mark":

 store.com/monitors/LCD/LG 

"Maximum Resolution":

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

So, to summarize, the URL structure will look something like this:

 /category/filter1/filter2/filter3 

I can’t figure out how to do this. The problem is that filters can be variables. I think the view will need to use **kwargs , but I'm not sure.

Do you have any idea how to fix such parameters?

Thanks a lot!

+4
source share
3 answers

Ben, I hope this helps 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 
+3
source

You can add this to your URLs:

 url(r'^(?P<category>\w)/(?P<filters>.*)/$', 'myview'), 

And then myview will get the category and filter options. You can divide the filters into "/" and search for each part in the "Filters" table.

It makes sense?

+1
source

how are you going to decide which aspect is filtered? Do you have a list of accepted keywords for each category? those. how does the server know that

 /LCD/LG/ 

means type=LCD, brand=LG

but

 /LG/LCD 

does not mean type=LG, brand=LCD , etc.

Is there a reason why you don't want to use GET parameters, for example.

 .../search/?make=LD&size=42 
0
source

Source: https://habr.com/ru/post/1385345/


All Articles