繁体   English   中英

登录后Django重定向

[英]Django redirect after login

我在Django中创建了我的第一个应用程序,我决定要在每个视图上登录窗口(带有用户名/密码“登录”按钮的小窗口)。 从base.html:

<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))

但是我遇到了错误:

在模板中使用了{%csrf_token%},但是上下文没有提供该值。 这通常是由于未使用RequestContext引起的。 warnings.warn(“模板中使用了{{csrf_token%},但上下文未提供该值。这通常是由于未使用RequestContext引起的。”)

看起来您以错误的方式使用了redirect 此方法不支持参数context_instance。 参见docs

关于错误。 确保从request.META ['HTTP_REFERER']渲染页面的视图使用RequestContext或手动导入并使用处理器生成CSRF令牌( docs )。

该错误表明CSRF令牌不在您的上下文中。 一本好书,了解CSRF的含义: 这里

为了生成CSRF令牌,请在设置中启用中间件,或在视图中手动生成,然后将其传递给模板。 我强烈建议您启用中间件:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM