How to redirect to another page

Jacobian

Well, I have my own session and authentication routines in my app. When a user goes to app/login/ page, if he or she is not loggen in, then he/she sees a form to submit, otherwise I want to redirect the user to the root page app/. login view looks like this:

def index(request):
    if sessionCheck(request):
        # here I want to redirect one level above to app/
        pass
    else:
        template = loader.get_template('login/login.html')
    ... other code which is not important

In PHP, I think, I would do it like this:

header("Location: /");
exit;

But how should I do exactly the same thing in Django?

Wtower

You can use the redirect shortcut function:

from django.shortcuts import redirect
return redirect('some-view-name')

You can also specify a URL apart from a named view. So if your index url does not have a name, you can specify '/'.

This shortcut function is essentially the same as:

from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
return HttpResponseRedirect(reverse('some-view-name'))

In order to have a named view, in your urls.py you have to provide a name argument. For instance:

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^some-view$', views.something, name='some-view-name'),
]

More on that on Django tutorial, Django URL dispatcher.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related