问题
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!
回答1:
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
回答2:
You could add this to your urls:
url(r'^(?P<category>\w)/(?P<filters>.*)/$', 'myview'),
And then myview would get the parameters of category and filters. You could split filters on "/" and search for each part within the Filters table.
Does that make sense?
回答3:
how do you intend to decide what aspect is being filtered by? Do you have a list of accepted keywords for each category? ie how does the server know that
/LCD/LG/
means type=LCD, brand=LG
but
/LG/LCD
doesn't mean type=LG, brand=LCD
etc
Is there any reason you don't want to use GET params, e.g.
.../search/?make=LD&size=42
来源:https://stackoverflow.com/questions/8432363/django-variable-parameters-in-urlconf