Django - Dynamic view for url

杀马特。学长 韩版系。学妹 提交于 2019-12-11 03:44:32

问题


I want to load a particular view depending on the url, for example:

url(r'^channel/(?P<channel>\d+)/$', ---, name='channel_render'),

Depending on the channel passed into the url, I want to load a specific view file. I tried doing this:

def configure_view(channel):
    print channel

urlpatterns = patterns('',
    url(r'^channel/(?P<channel>\d+)/$', configure_view(channel), name='channel_render'),

But obviously the channel argument is not getting passed in. Is there any way to do this? The only other solution I can think of is loading a manager view and then loading the relevant view file from there. If this is the only way, how do I redirect to another view file from within a view?


回答1:


I think the easiest way to do this is to load a view that functions as a tiny dispatcher, which calls the final view you're interested in.

As far as how to do that, views are just functions that get called in a particular way and expected to return a particular thing. You can call one view from another; just make sure you're properly returning the result.

You can load views from different files with import.




回答2:


You could do something like this.

#urls.py
url(r'^channel/(?P<channel>\d+)/$', switcher, name='channel_render'),

#views.py
def switcher(request, channel):
    if channel == 'Whatever':
        return view_for_this_channel()

def view_for_this_channel()
    #handle like a regular view

If using class-based views, the call in your switcher() will look like this:

#views.py
def switcher(request, channel):
    if channel == 'Whatever':
        return ViewForThisChannel.as_view()(request)  # <-- call to CBV

def ViewForThisChannel(View):
    #handle like a regular class-based view



回答3:


For redirecting you should use the Django redirect shortcut function:

from django.shortcuts import redirect

def my_view(request):
    ...
    return redirect('some-view-name', foo='bar')

https://docs.djangoproject.com/en/1.7/topics/http/shortcuts/#redirect




回答4:


try calling like a normal view e.g.

def configure_view(request, channel):
    print channel

url(r'^channel/(?P<channel>\d+)/$', configure_view, name='channel_render'),


来源:https://stackoverflow.com/questions/6073679/django-dynamic-view-for-url

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