CSRF验证失败。请求被中止。

26

我尝试构建一个非常简单的网站,用户可以将数据添加到sqlite3数据库中。我有一个POST表单,其中包含两个文本输入框。

index.html:

{% if top_list %}
    <ul>
    <b><pre>Name    Total steps</pre></b>
    {% for t in top_list %}
        <pre>{{t.name}} {{t.total_steps}}</pre>
    {% endfor %}
    </ul>
    {% else %}
    <p>No data available.</p>
{% endif %}
<br>
<form action="/steps_count/" method="post">
    {% csrf_token %}
    Name: <input type="text" name="Name" /><br />
    Steps: <input type="text" name="Steps" /><br />
   <input type="submit" value="Add" />
 </form>

forms.py:

from django import forms
from steps_count.models import Top_List

class Top_List_Form(forms.ModelForm):
    class Meta:
        model=Top_List

views.py:

# Create your views here.
from django.template import Context, loader
from django.http import HttpResponse
from steps_count.models import Top_List
from steps_count.forms import Top_List_Form
from django.template import RequestContext
from django.shortcuts import get_object_or_404, render_to_response

def index(request):

if request.method == 'POST':
    #form = Top_List_Form(request.POST)
    print "Do something"
else:
    top_list = Top_List.objects.all().order_by('total_steps').reverse()
    t = loader.get_template('steps_count/index.html')
    c = Context({'top_list': top_list,})
    #output = ''.join([(t.name+'\t'+str(t.total_steps)+'\n') for t in top_list])
    return HttpResponse(t.render(c))

然而,当我点击“提交”按钮时,出现了403错误:
CSRF verification failed. Request aborted.

我已经在index.html中包括了{% csrf_token %}。然而,如果这是一个请求上下文的问题,我真的不知道在哪里以及如何使用它。我希望所有的事情都发生在同一页(index.html)上。


请确保您的浏览器接受 cookies。 - Gabriel Ben Compte
15个回答

20

您可能忘记在表单中添加以下内容:

{% csrf_token %}


11

将其添加到设置文件中。

CSRF_TRUSTED_ORIGINS = [
    'https://appname.herokuapp.com'
]

clear, easy and simple - Adiii

9

当您遇到此类消息时,意味着CSRF令牌丢失或不正确。因此,您有两个选择。

  1. For POST forms, you need to ensure:

    • Your browser is accepting cookies.

    • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.

  2. The other simple way is just commented one line (NOT RECOMMENDED)('django.middleware.csrf.CsrfViewMiddleware') in MIDDLEWARE_CLASSES from setting tab.

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

    )


谢谢第二部分。我只是不需要它! :) - SaurabhJinturkar
13
关闭 CSRF 并不是解决方案,请不要这样做。(回答的第二部分) - elnygren

6

另一个最好的解决方法是使用'@csrf_exempt'注释。

Django 3.1.1中,您可以只需在方法上使用@csrf_exempt

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def index(request):

你不需要在html中指定{% csrf_token %}

学得愉快!


应该使用 from django.views.csrf.decorators import csrf_exempt 而不是 from django.views.decorators import csrf_exempt - Pacha
这是我在使用Django 3.1.1时有效的解决方案,但你需要从django.views.decorators.csrf中导入csrf_exempt。 - Joseph

3
一个常见的错误是使用render_to_response(这在较旧的教程中常用),它不会自动包含RequestContext。而render会自动包含它。
当我按照教程创建新应用程序时,发现CSRF在新应用程序的页面上无法正常工作时,了解到了这一点。

2
在你的HTML头部中,添加:

<meta name="csrf_token" content="{{ csrf_token }}">

然后在你的JS/angular配置文件中:

app.config(function($httpProvider){
    $httpProvider.defaults.headers.post['X-CSRFToken'] = $('meta[name=csrf_token]').attr('content');
}

2

如果您正在使用 DRF,您需要添加 @api_view(['POST'])


0
我遇到了相同的错误:
CSRF验证失败。请求被中止。
因为我在
中没有设置csrf_token标签,并且使用了method="post",如下所示:
<form action="{% url 'account:login' %}" method="post">
  {% comment %} {% csrf_token %} {% endcomment %}
  ...
</form>

所以,我在以下的<form></form>标签中设置了csrf_token,并将method="post",这样错误就解决了。
<form action="{% url 'account:login' %}" method="post">
  {% csrf_token %}
  ...
</form>

此外,无论您是否在以下所示的<form></form>中使用method="get"设置csrf_token标签,都不会出错。*只能将getpost请求方法设置为<form></form>method,而不能设置headput等方法,详见答案
<form action="{% url 'account:login' %}" method="get">
  {% comment %} {% csrf_token %} {% endcomment %}
  ...
</form>

<form action="{% url 'account:login' %}" method="get">
  {% csrf_token %}
  ...
</form>

0
请确保您的浏览器接受cookies。我也遇到了同样的问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接