2013-01-20 32 views
0

我知道這個問題已經回答了重定向是一個或另一種方式,但我仍然無法弄清楚如何在用戶登錄後重定向。我知道Django自帶了內置的網站,但我需要一個自定義登錄表單,它看起來像這樣(這是HTML):的Django的Python登錄後

{% if user.is_authenticated %} 
    <!-- Authenticate account menu --> 
{% else %} 
    <h3>Login</h3> 
    <form action="/app/login/" method="post" accept-charset="utf-8"> 
     <label for="username">Username</label> 
     <input type="text" name="username" value="" id="username" /> 
     <label for="password">Password</label> 
     <input type="password" name="password" value="" id="password" /> 
     <p><input type="submit" value="Login →"></p> 
    </form> 
{% endif %} 

我views.py看起來像這樣:

from django.http import HttpResponse 
from django.shortcuts import render_to_response 
from django.template import Context, loader 
from django.contrib.auth import authenticate, login 
from django.views.generic.simple import * 

def index(request): 
if request.method == 'POST': 
     user = authenticate(username=request.POST['username'],     password=request.POST['password']) 
     if user is not None: 
      if user.is_active: 
       login(request, user) 
       # success 
      if request.POST['next']: 
       return HttpResponseRedirect(request.POST['next']) 
      else: 
       return HttpResponseRedirect('/') 
     else: 
      # disabled account 
      return direct_to_template(request, 'inactive_account.html') 
    else: 
     # invalid login 
     return render_to_response("app/index.html") 
return render_to_response("app/index.html") 

我並沒有完全寫代碼自己。我發現重定向發生在這裏的html文件中:<form action="/app/login/。但django說它無法找到網址。總而言之,我不得不說我是網絡編程+ django + python的新手,並且不完全清楚這個概念。 感謝您的幫助!

+0

您在'authenticate(username = request.POST ['username']''中缺少'''',並且您的縮進不正確。請更新您的問題,併發布您的'urls.py'。 –

回答

0

login(request, user)後,您需要返回的HTTP響應,例如,它是從OME模板呈現的頁面。但是,如果你想要去其他一些網頁,你可以返回HttpResponseRedirect('/needed_url'),你會得到針對性的URL的請求。

您也可以點request.POST['referrer'])根據需要鏈接直接轉到上一頁。

Django Docs - HttpResponseRedirect

附:另外我可以說<form action="/some/url/" ...指出你要管理你的表單數據的地址。如果使用Django,你應該有一個記錄在您的urls.py文件中像(r'^some/url/$', some_function),將處理您指定的功能要求。

+0

從這個問題看,正如作者說,他不寫代碼自己完全他已經返回'HttpResponseRedirect',所以不能成爲問題。 –

+0

,所以我想這個問題是在哪裏的URL寫去登錄後去。 – birdy90