2010-10-21 31 views
1

我有一個簡單的表單,我希望用戶能夠登錄;這裏是帶有CSRF標籤的模板代碼:Django中的CSRF錯誤;我如何將CSRF添加到我的登錄視圖?

<html> 
<head><title>My Site</title></head> 

<body> 
    <form action="" method="post">{% csrf_token %} 
     <label for="username">User name:</label> 
     <input type="text" name="username" value="" id="username"> 
     <label for="password">Password:</label> 
     <input type="password" name="password" value="" id="password"> 

     <input type="submit" value="login" /> 
     <input type="hidden" name="next" value="{{ next|escape }}" /> 
    </form> 
</body> 
</html> 

現在這裏是我的views.py頁面。問題是我在哪裏放置CSRF支持部分(現在我得到一個CFRS令牌錯誤)在我看來,我該怎麼做?

from django.contrib import auth 

def login_view(request): 
    username = request.POST.get('username', '') 
    password = request.POST.get('password', '') 
    user = auth.authenticate(username=username, password=password) 
    if user is not None and user.is_active: 
     # Correct password, and the user is marked "active" 
     auth.login(request, user) 
     # Redirect to a success page 
     return HttpResponseRedirect("/account/loggedin/") 
    else: 
     # Show an error page 
     return HttpResponseRedirect("account/invalid/") 

def logout_view(request): 
+0

正常情況下,CSRF已被請求上下文處理器佔用。你會得到什麼錯誤? – 2010-10-21 00:51:49

回答

5

你必須在RequestContext添加到認爲呈現在它與{% csrf_token %}線的頁面。下面是從tutorial的例子:

# The {% csrf_token %} tag requires information from the request object, which is 
# not normally accessible from within the template context. To fix this, 
# a small adjustment needs to be made to the detail view, so that it looks 
# like the following: 
# 
from django.template import RequestContext 
# ... 
def detail(request, poll_id): 
    p = get_object_or_404(Poll, pk=poll_id) 
    return render_to_response('polls/detail.html', {'poll': p}, 
          context_instance=RequestContext(request)) 

context_instance=RequestContext(request)部分是重要的組成部分。這使得RequestContext在呈現時可用於表單模板。