Django:URLconf中的变量参数 [英] Django: variable parameters in URLconf

查看:201
本文介绍了Django:URLconf中的变量参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找这个问题,找不到任何对不起,如果它是重复的。

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

我正在建立某种电子商务网站,类似于易趣。当我试图浏览类别和过滤器时,我出现了这个问题。例如。您可以浏览监视器类别。这将显示您的大量显示器和一些过滤器(与ebay完全相同)来应用它们。所以,你去监视器,然后你有过滤器:

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:


  • 类型:LCD - LED - CRT

  • 品牌:ViewSonic - LG - 三星

  • 最大分辨率:800x600 - 1024x768

这些过滤器将被附加到URL上,在示例之后,当您浏览监视器时,URL可能类似于:

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

品牌:

store.com/monitors/LCD/LG

最大分辨率:

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

所以,总结一下,URL结构将是一些东西像:

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

/category/filter1/filter2/filter3

我无法弄清楚如何做到这一点。问题是过滤器可以是变量。我认为在这个意见中需要使用 ** kwargs 但我不太确定。

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?

非常感谢!

推荐答案

Ben,我希望这将有助于您

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

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

这篇关于Django:URLconf中的变量参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆