2014-09-21 323 views
0

我在Django創建我的第一個應用程序 我決定我想在每個視圖上記錄窗口(小一個用戶名/密碼爲「登錄」按鈕)。 從base.html文件:Django登錄後重定向

<div id="logging"> 
    {% if user.is_authenticated %} 
    <h1>Witaj, {{user.username}}!</h1> 
    {% else %} 
    <form method="post" action="{% url 'harcowanie.views.login' %}"> 
    {% csrf_token %} 
    <div style="display: inline-block;"> 
    <p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="30" /></p> 
    <p><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></p> 
    </div> 
    <div style="display: inline-block; position: relative; bottom: 25px;"> 
    <input class="decent_background" type="submit" value="Log in" /> 
    </div> 
</form> 
{% endif %} 
    </div> 

我views.py的任何部分:

def login(request): 
    username = request.POST['username'] 
    password = request.POST['password'] 
    user = authenticate(username=username, password=password) 
    if user is not None: 
     if user.is_active: 
      login(request=request, user=user) 
      return redirect(request.META['HTTP_REFERER'], context_instance=RequestContext(request)) 
     else: 
      pass 
      # Return a 'disabled account' error message 
    else: 
     pass 
     # Return an 'invalid login' error message. 

    return redirect(request.META['HTTP_REFERER'], context_instance=RequestContext(request)) 

但我發現了錯誤:就像你在錯誤的方式使用redirect

A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.")

回答

2

看起來。此方法不支持參數context_instance。見docs

關於錯誤。確保從request.META ['HTTP_REFERER']使用RequestContext呈現頁面的視圖,或手動導入並使用處理器生成CSRF標記(docs)。

+0

感謝它似乎解決了我的問題。 – 2014-09-21 18:57:17

0

錯誤指出CSRF令牌不在您的上下文中。瞭解CSRF的內容:here

爲了生成CSRF令牌,請在您的設置中啓用中間件,或在視圖中手動生成,然後將其傳遞到您的模板。我強烈建議你啓用中間件:)