gpt4 book ai didi

django - CSRF验证失败。请求被中止。 CSRF cookie 未设置

转载 作者:行者123 更新时间:2023-12-02 07:10:39 24 4
gpt4 key购买 nike

错误:

Reason given for failure: CSRF cookie not set.

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function uses RequestContext for the template, instead of Context. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using the CSRF_FAILURE_VIEW setting.

做了我能找到的一切,但没有任何帮助,一定是非常愚蠢的事情((

我的模板

<form method="POST">{% csrf_token %}
{% for field in form %}
<div class="control-group">
{{ field }}
</div>
{% endfor %}
<input type="Submit" id="fsubmit" class="btn btn-primary btn-large btn-block" value='Register'/>
</form>

我的Views.py

from django.shortcuts import render_to_response
from django.template import RequestContext

def register_user(request):
context = {}
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
pass
else:
form = RegisterForm(auto_id=False)
context['form'] = form
return render_to_response('templates/register.htm',context, context_instance=RequestContext(request))

设置

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',

)

最佳答案

使用 csrf_exempt 来避免 csrf token 。

在 View 中

从 django.views.decorators.csrf 导入 csrf_exempt

@csrf_exempt
def register_user(request):
context = {}
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
pass
else:
form = RegisterForm(auto_id=False)
context['form'] = form
return render_to_response('templates/register.htm',context, context_instance=RequestContext(request))

关于django - CSRF验证失败。请求被中止。 CSRF cookie 未设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24456481/

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