gpt4 book ai didi

python - Django 抛出 "CSRF token missing or incorrect"错误(因为 csrfmiddlewaretoken 的空值)

转载 作者:行者123 更新时间:2023-11-28 19:30:26 29 4
gpt4 key购买 nike

我最近遇到了一个很奇怪的问题。我的模板中有一个表单,如下所示:

<form class="form" id="loginForm" role="form" action="/user/login/" 
method="POST">
{% csrf_token %}
<div class="form-group">
<input type="email" class="form-control" id="email" name="email"
placeholder="Enter email" value="">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password"
name="password" placeholder="Password" value="">
</div>
<div class="cl-effect-7">
<button type="submit" class="btn btn-primary">SIGN IN</button>
</div>
</form>

我收到了 CSRF token 丢失或不正确。进一步深入挖掘,我发现虽然 csrftoken cookie 在浏览器中设置正确,但 POST 请求的 csrfmiddlewaretoken 为空值,因此它会抛出上述原因的错误.
这也是我的看法(虽然我怀疑它是否有任何问题)

def user_login(request):
context = RequestContext(request)
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user = authenticate(username=email, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/user/')
else:
return HttpResponse("Your account is disabled.")
else:
return HttpResponse("Invalid login details supplied.")
else:
return render_to_response('user/login.html', {},context_instance = context)

这是重定向到 login.html 的另一个 View :

def index(request):
context_dict = {}
template = "user/login.html" #default template to render
user = None
user_profile = None

user = request.user.id
if user != None:
user_profile,created = UserProfile.objects.get_or_create(user=user)

#Check whether the user is new,if yes then he needs to select btw Mentor-Mentee
if user_profile and user_profile.is_new:
context_dict['selected'] = None
template = "user/select.html" #User has to select either Mentor/Mentee,so redirect to select.html


return render_to_response(template,context_dict,context_instance = RequestContext(request))

现在我使用了很少的 JavaScript 来解决这个问题,方法是手动从 cookie 设置 csrfmiddlewaretoken 的值,但这对 Django 来说有点奇怪。
PS:我使用的是 Django 1.7 并在所有浏览器上进行了测试。

最佳答案

尝试将此添加到您的表单中:

<div style="display:none">
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
</div>

来源:https://docs.djangoproject.com/en/dev/ref/csrf/#other-template-engines

关于python - Django 抛出 "CSRF token missing or incorrect"错误(因为 csrfmiddlewaretoken 的空值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27722347/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com