python - django如何一个url绑定多个视图
PHP中文网
PHP中文网 2017-04-18 09:13:26
0
2
433

问题很简单,我有2个url规则,但是可能会有冲突

url(r'^(?P<category>\w+)/$',
            CategoryView.as_view(), name='category-detail-view'),


url(r'^(?P<url>\w+)/$',CustomView.as_view(),name="custm"),

简单的看来就是这样的,这2条url,其实目的的是一样,为了访问
www.baidu.com/xxx/ 这样的分类,只是有一个是自定页面.
这样设置不行,只能取其中一个.

我想问问, django有没有办法让同一个url规则绑定多个不同的视图? 这样就很灵活了~

PHP中文网
PHP中文网

认证0级讲师

reply all(2)
左手右手慢动作

If a url pattern can be bound to multiple views, I think Django doesn’t know how to handle this request (which view should be sent to it).

But your question now is:

Different URLs that match the same pattern require different processing

This sounds weird. If this is the case, it probably means that your pattern should not be written like this. You should try to split the original url pattern into multiple distinguishable patterns.

Of course, it is very likely that the url pattern is difficult to separate. In your example, it may indeed be difficult to distinguish:

(domain name)/category1/

and

(domain name)/www.google.com.tw/

Because the patterns extracted from these two URLs are basically exactly the same as you said.

The following are several possible ways:

  1. If there are not many categories, you can consider directly splitting the category part to write the url pattern

  2. Just use a url pattern, but first use a unified view to process it, and then forward it to different views for processing based on the parameters intercepted from the url


Conclusion:

URL interception parameters are just for this need:

The same form of url pattern must be able to handle various urls that match the pattern but are actually different

伊谢尔伦
# get_all_categories() 获取所有分类
category_pattern = '|'.join([category for category in get_all_categories()])

url(r'^(?P<category>%s)/$' % category_pattern, CategoryView.as_view(), name='category-detail-view'),

url(r'^(?P<url>\w+)/$',CustomView.as_view(),name="custm"),
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template