Django 403 CSRF验证失败 [英] Django 403 CSRF Verification Failed

查看:65
本文介绍了Django 403 CSRF验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的学校编写一个注册网站,并使用Django作为框架.对于注册,我需要一个用户名,密码和注册令牌.那些尚未验证的内容,我现在正试图从注册输入页面(使用POST请求)转到您已成功注册"页面.沿线的某个地方,csrf令牌显然拒绝被验证.

I'm writing an enrollment website for my school, and using Django for the framework. For the registration, I require a username, password, and registration token. Those have yet to be validated, all I'm attempting to do right now is go from the registration input page (which uses a POST request) to a "You have successfully registered" page. Somewhere along the line, the csrf token is apparently refusing to be validated.

我的观点:

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/时,它将返回我请求的页面,没有错误.

When I attempt to go from the registration page to the success page, it gives me an error 403 (CSRF Verification failed. Request aborted). However, when I attempt to go to the url mysite.com/register/, it returns the page I requested with no error.

有什么办法可以解决这个问题?我一直在研究RequestContext,但是我不确定要在哪里使用它.

Is there any way to fix this? I've been looking at RequestContext, but I'm not entirely sure where it would be used.

推荐答案

使其正常工作.Daniel是对的-这是我的中间件配置的问题.我在settings.py的中间件数组之前添加了两行,突然之间一切正常.

Got it to work. Daniel was right - it was a problem with the configuration of my middleware. I added two lines before my middleware array in settings.py, and all of the sudden it worked.

SESSION_COOKIE_SECURE = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

我不能完全确定为什么会起作用,或者问题出在什么地方,但是现在可以起作用了.谢谢丹尼尔!

I can't say I'm entirely sure why it worked, or what the issue was exactly, but it works now. Thanks Daniel!

这篇关于Django 403 CSRF验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆