Django:URLconf中的可变参数
我一直在找这个问题,但没找到,抱歉如果这重复了。
我正在搭建一个类似于eBay的电商网站。我的问题出现在我尝试浏览“分类”和“过滤器”时。例如,你可以浏览“显示器”这个分类。这样就会显示很多显示器,还有一些过滤器(和eBay的一样)可以应用。你进入“显示器”后,会有这样的过滤器:
- 类型:LCD - LED - CRT
- 品牌:ViewSonic - LG - Samsung
- 最大分辨率:800x600 - 1024x768
这些过滤器会被添加到网址中,举个例子,当你浏览显示器时,网址可能会是这样的:
store.com/monitors
如果你应用了“类型”过滤器:
store.com/monitors/LCD
“品牌”:
store.com/monitors/LCD/LG
“最大分辨率”:
store.com/monitors/LCD/LG/1024x768
所以,总结一下,网址结构可能是这样的:
/category/filter1/filter2/filter3
我真的不知道该怎么做。问题是过滤器可能是变化的。我觉得在视图中需要使用 **kwargs
,但我不太确定。
你有没有什么想法,如何捕捉这些参数?
非常感谢!
3 个回答
0
你打算怎么决定要过滤哪个方面的信息呢?你有没有为每个类别准备一个接受的关键词列表?比如,服务器是怎么知道
/LCD/LG/
代表的是 type=LCD, brand=LG
但
/LG/LCD
并不代表 type=LG, brand=LCD
等等呢?
你有没有什么特别的原因不想使用 GET 参数,比如
.../search/?make=LD&size=42
1
你可以把这个加到你的网址里:
url(r'^(?P<category>\w)/(?P<filters>.*)/$', 'myview'),
这样的话,myview就能获取到类别和过滤器的参数。你可以用“/”来分割过滤器,然后在过滤器表里查找每一部分。
这样说清楚了吗?
3
本,希望这能帮到你。
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
或者
def catalog_products_view(request, category, **kwargs):
filter1 = kwargs['filter1']
filter2 = kwargs['filter2']
....
filterN = kwargs['filterN']
# some code here