search

Home  >  Q&A  >  body text

python - django如何一个url绑定多个视图

问题很简单,我有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中文网2865 days ago430

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 09:15:26

    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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:15:26

    # 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"),

    reply
    0
  • Cancelreply