2013-07-11 51 views
0

我試圖實現一個簡單的頁面重定向到索引頁面,如果用戶身份驗證失敗。Django - 退出時如何重定向到索引頁?

想象一下,我有兩條路:

www.xyz.com/app/ 
www.xyz.com/app/user 

第一個呈現的索引頁,第二個是在成功登錄的授權用戶登陸頁面。

在我views.py文件,我有

def index(request): 
    return render(request, "app/index.html") 

def userLogin(request): 
    loginUser = authenticate(username = request.POST["username"], password = request.POST["password"]) 

    if loginUser is not None: 
    if not loginUser.is_active: 
     loginUser.is_active = True 
     loginUser.save() 

     login(request, loginUser) 
     return HttpResponse(reverse(user))  
    else: 
     return HttpResponse(simplejson.dumps({"login" : "failed"})) 

def userLogout(request): 
    logout(request) 
    return HttpResponseRedirect(reverse(index)) 

urls.py

urlpatterns = patterns("", 
    url(r'^$', views.index, name = "index"), 
    url(r'^user/$', views.user, name = "user"), 
    url(r'^registerNewUser/$', views.registerNewUser), 
    url(r'^userLogin/$', views.userLogin), 
    url(r'^user/userLogout/$', views.userLogout), 
) 

註銷功能通過一個Ajax POST請求訪問,並在日誌中,我看到

[11/Jul/2013 09:08:00] "POST /app/user/userLogout/ HTTP/1.1" 302 0 
[11/Jul/2013 09:08:00] "GET /app/ HTTP/1.1" 200 5039 

但索引頁未加載。但是,如果我刷新頁面,索引頁面會加載,因爲有條件的調用request.user.is_authenticated()會觸發相同的HttpResponseRedirect調用和參數失敗。

+0

你的['LOGOUT_URL'](https://docs.djangoproject.com/en/dev/ref/settings/#logout-url)設置是什麼樣子的? – karthikr

+0

'LOGOUT_URL =「/ app /」'是我放在我的設置文件中。它不起作用,「/ app/index.html' – Jason

+0

也沒關係:'(r'^ user/userLogout/$','django.contrib.auth.views.logout', {'next_page' :'/ app /'})'? – karthikr

回答

0
If login fail i mean in else case return render(request, "app/index.html") instead 
of return HttpResponse(simplejson.dumps({"login" : "failed"})) 

**updated userLogin** 

def userLogin(request): 
    loginUser = authenticate(username = request.POST["username"], 
    password = request.POST["password"]) 

if loginUser is not None: 
if not loginUser.is_active: 
    loginUser.is_active = True 
    loginUser.save() 

    login(request, loginUser) 
    return HttpResponse(reverse(user))  
else: 
    return render(request, "app/index.html")