2014-09-21 171 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令牌,请在您的设置中启用中间件,或在视图中手动生成,然后将其传递到您的模板。我强烈建议你启用中间件:)