简体   繁体   中英

redirecting from view to another html page with another url slug in Django 1.6

I have a view (login view). which will be used by /login/ url.

I mean http://<base-url>/login/

in urls.py i'm doing url(r'^login/$',myapp.views.login)

def login(request,template='login.html'):
     #do login stuff
     If successfully logged-in:
          then redirect to new html page with new url let say '/home/'
     else:
         show same login page again and ask user to enter valid credentials  

so if a user successfully login I want to redirect/transfer to the new link http://<base-url>/home/ and this should be associate to "home.html" file in template folder(where "login.html" is already)

now on this home.html I have a form (ask user to enter few things in text boxes.) and at the end of this home page there is submit button after clicking on this submit button I'll save all entered detail in DB. I can Do all these things but I'm stucked at redirecting part (I'm able to change the html page (i mean after succesfully login this shows content of "home.html"))

but I'm unable to change the url slug. it is still /login/ but I want it to be /home/ .

as obviously I have another view for home.html which will handle saving the data from form to DB.

What you need to do is have the login view return a redirect on success. For example:

from django.http import HttpResponseRedirect

def login(request, template='login.html'):
    if successfully logged in:
        return HttpResponseRedirect('/home/')
    ...

In this case, /home/ will need to be another entry in your urls.py and another view. For example:

urls.py:

url(r'^home/$', 'myapp.views.home'),

views.py:

def home(request):
    return render(request, 'home.html')
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

def login(request):
     If success:
        return HttpResponseRedirect(reverse('home.view'));

in your urls.py

url(r'^home/$', 'home', name='home.view')

and your home view will look like

def home(request):
    return render(request, 'home.html');

This is somewhat similar to the answer given by Joey, as django document advised write once so will prefer writing reverse

DOC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM