django Url endswith regex in url path

孤街浪徒 提交于 2020-01-17 01:45:07

问题


I need to support following urls in single url regex.

/hotel_lists/view/
/photo_lists/view/
/review_lists/view/

how to support all above urls in single views?

I tried something like below

url(r'^\_lists$/(?P<resource>.*)/$', 'admin.views.customlist_handler'),

edit: hotel,photo, review is just example. that first part will be dynamic. first part can be anything.


回答1:


If you wish to capture the resource type in the view, you could do this:

url(r'^(?P<resource>hotel|photo|review)_lists/view/$', 'admin.views.customlist_handler'),

Or to make it more generic,

url(r'^(?P<resource>[a-z]+)_lists/view/$', 'admin.views.customlist_handler'), #Or whatever regex pattern is more appropriate

and in the view

def customlist_handler(request, resource):
    #You have access to the resource type specified in the URL.
    ...

You can read more on named URL pattern groups here



来源:https://stackoverflow.com/questions/33086369/django-url-endswith-regex-in-url-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!