Django 403 CSRF 验证失败

Django 403 CSRF Verification Failed

我正在为我的学校编写一个招生网站,并使用 Django 作为框架。对于注册,我需要用户名、密码和注册令牌。这些还有待验证,我现在要做的就是从注册输入页面(使用 POST 请求)转到 "You have successfully registered" 页面。沿线的某个地方,csrf 令牌显然拒绝被验证。

我的看法:

def register(request):
    return render(request, 'enroller/successfulEnroll.html')

我的页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="{% url 'register' %}" method="post"> {% csrf_token %}
    <div class="container">
        <label><b>New Username</b></label>
        <input type="text" placeholder="Username" name="uname" required>
        <br>
        <label><b>Password</b></label>
        <input type="password" placeholder="Password" name="psw" required>
        <br>
        <label><b>Registration Password</b></label>
        <input type="text" placeholder="Registration Key" name="reg" required>
        <br>
        <input type="submit" value="Register" />
    </div>
    </form>
</body>
</html>

当我尝试从注册页面转到成功页面时,出现错误 403(CSRF 验证失败。请求中止)。但是,当我尝试访问 url mysite.com/register/ 时,它 returns 我请求的页面没有错误。

有什么办法可以解决这个问题吗?我一直在查看 RequestContext,但我不完全确定它会用在哪里。

开始使用了。丹尼尔是对的——这是我的中间件配置的问题。我在 settings.py 中的中间件数组前添加了两行,突然间它就起作用了。

SESSION_COOKIE_SECURE = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

我不能说我完全确定它为什么起作用,或者问题到底是什么,但它现在起作用了。谢谢大牛!

也许你可以用这个方法。 djang 版本是 1.11.1

from django.shortcuts import render
from django.template.context_processors import csrf

form = LoginForm()
c = {'form': form}
c.update(csrf(request))
return render(request, 'a_template.html', c)

我在 http://djangobook.com/security-in-django/ 找到了这个方法
对我来说,做工还行,但不是最好的,因为不止一条线。