Django url.py 具有相同正则表达式名称模式的不同视图函数
我正在过滤一些类别(cat1、cat2、cat3),以由不同的视图呈现,然后由其他视图函数呈现所有其余类别。每次添加类别名称时,不断向 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'),
)
I'm filtering a few categories (cat1, cat2, cat3) to be rendered by different views then all the rest by other view functions. It is getting unwieldy to keep adding category slugs to the urlpatterns each time one is added. Can I factor that part out of the regex some how?
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'),
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我个人会将这个逻辑放在视图中而不是 urlspatterns 中。
我将创建一个所有特殊类别的列表,因此:
然后对于您的视图,您可以执行以下操作:
然后,当您添加新的特殊类别时,只需将其添加到该列表中
I'd personally put this logic in the view rather than the urlspatterns.
I would create a list of all the special categories so for this:
Then for you view you can do something like this:
Then when you add a new special category, you just need to add it to that list