开发者

In Django, can you automatically map URLs to view methods?

Given a view like this:

# my_app/views.py
def index(request):
    ...
def list(request):开发者_运维知识库
    ...
def about(request):
    ...

Instead of explicitly declaring the urls in urls.py for each method in the view:

# urls.py
url(r'^index$', 'my_app.views.index'),
url(r'^list$', 'my_app.views.list'),
url(r'^about$', 'my_app.views.about'),
...

Is it possible to just give the URL dispatcher the view (my_apps.views) and have it handle all the view's methods?


I suppose you can have one view that captures a url regexp,

r'^(?P<viewtype>index|list|about)/$', 'myview'

with a view that handles the captured parameter.

def myview(request, viewtype):
    if viewtype == 'index':
          return http.HttpResponse("I'm the index view")
    elif viewtype == 'list':
          return http.HttpResponse("I'm the list view')

But I'd really recommend keeping your view logic separated for clarity. It's much easier to follow 3 different views with their specific functions than 3 if / then statements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜