2

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?

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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 Comments

I'd rather load the view in the same way django does when the URL is resolved, just cold importing the view doesn't seem right? I'll have a look through the source code and see how django imports views, perhaps there is a function I can hijack.
Seems I could use import_module from django.utils.importlib. Thanks.
0

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'),

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.