python - Django url.py 具有相同正则表达式名称模式的不同 View 函数

标签 python django django-urls

我正在过滤一些类别(cat1、cat2、cat3),以由不同的 View 呈现,然后由其他 View 函数呈现所有其余类别。每次添加类别名称时,不断向 urlpattern 添加类别名称会变得很麻烦。我可以如何将该部分从正则表达式中分解出来吗?

urlpatterns = patterns('catalog.category_views',
    (r'^(?P<cat_slug>(cat1|cat2|cat3))/$', 'universal_category'),
    (r'^(?P<cat_slug>(cat1|cat2|cat3))/(?P<subcat_slug>[-\w]+)/$', 'subcat_listing'),
    (r'^(?P<cat_slug>(cat1|cat2|cat3))/part/(?P<part>[-\w]+)/$', 'subcat_product'),
)

urlpatterns += patterns('catalog.make_views',
    (r'^(?P<cat_slug>[-\w]+)/$', 'category'),
    (r'^(?P<cat_slug>[-\w]+)/(?P<make_slug>[-\w]+)/$', 'make'),
    (r'^(?P<cat_slug>[-\w]+)/(?P<make_slug>[-\w]+)/(?P<model_slug>[-\w]+)/(?P<year_low>\d{4})-(?P<year_high>\d{4})/$', 'listing'),
    (r'^(?P<cat_slug>[-\w]+)/part/(?P<part>[-\w]+)/$', 'product'),
)

最佳答案

我个人会将这个逻辑放在 View 中而不是 urlspatterns 中。

我将创建一个所有特殊类别的列表,因此:

special_cats = ['cat1','cat2','cat3']

然后你可以看到你可以做这样的事情:

def generic_cat_view(request, cat_slug):
    if cat_slug in special_cats:
        return special_view(request, cat_slug)
    else:
        #generic view

然后,当您添加新的特殊类别时,只需将其添加到该列表中即可

关于python - Django url.py 具有相同正则表达式名称模式的不同 View 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2367918/

相关文章:

python - 当 Chrome 浏览器工作时,Web Scraper 返回空的 html 文件;已经尝试过 UserAgent

python - Django:检查存在哪个相关对象

python - 在 Django 中,如何使用请求来确定其 URLconf View 名称?

python - 错误: 'NameError: name ' terms_and_conditions' is not defined' when it is

python - 将变量 urlname 传递给 django 模板中的 url 标签

python 情节9: color brewer not enough

python - 如何在 Robot Framework 中设置 FireFox 的首选项

python - NumPy 的大小维度中的 "."是什么?

javascript - 如何通过 AJAX post 请求将两个依赖下拉列表的值发送到 Django View ?

python - Django 说该表不存在