Hanpan
Hanpan

Reputation: 10251

Django - Dynamic view for url

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?

Upvotes: 2

Views: 4403

Answers (4)

phedoreanu
phedoreanu

Reputation: 2736

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

Upvotes: 2

silent1mezzo
silent1mezzo

Reputation: 2932

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

Upvotes: 4

JamesO
JamesO

Reputation: 25936

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

Upvotes: 0

Luke Sneeringer
Luke Sneeringer

Reputation: 9428

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.

Upvotes: 1

Related Questions