CSRF verification failed. Request aborted

2019-01-09 07:36发布

问题:

I try to build a very simple website where one can add data into sqlite3 database. I have a POST form with two text input.

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))

However, when I click the "submit" button, I get the 403 error:

CSRF verification failed. Request aborted.

I have included {% csrf_token %} in index.html. However, if it is a RequestContext problem, I really have NO idea on where and how to use it. I want everything to happen on the same page (index.html).

回答1:

Use the render shortcut which adds RequestContext automatically.

from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from steps_count.models import Top_List
from steps_count.forms import Top_List_Form


def index(request):

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


回答2:

When you found this type of message , it means CSRF token missing or incorrect. So you have two choices.

  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',
    

    )



回答3:

You should use

from django.shortcuts import render_to_response
.
.
.
return render_to_response("steps_count/index.html", {'top_list': top_list}, context_instance=RequestContext(request))

instead of

return HttpResponse(t.render(c))

read about "Context Processors" and see this link for details about how CSRF protection works in Django.

UPDATE

I misread the HttpResponse as render_to_response. I updated my previous answer.



回答4:

A common mistake here is using render_to_response (this is commonly used in older tutorials), which doesn't automatically include RequestContext. Render does automatically include it.

Learned this when creating a new app while following a tutorial and CSRF wasn't working for pages in the new app.



回答5:

You may have missed adding the following to your form:

{% csrf_token %}


回答6:

function yourFunctionName(data_1,data_2){
        context = {}
        context['id'] = data_1
        context['Valid'] = data_2
        $.ajax({
            beforeSend:function(xhr, settings) {
                    function getCookie(name) {
                            var cookieValue = null;
                            if (document.cookie && document.cookie != '') {
                                var cookies = document.cookie.split(';');
                                for (var i = 0; i < cookies.length; i++) {
                                    var cookie = jQuery.trim(cookies[i]);
                                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                                        break;
                                    }
                                }
                            }
                            return cookieValue;
                        }
                        if (settings.url == "your-url")
                            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                    },

            url: "your-url",
            type: "POST",
            data: JSON.stringify(context),
            dataType: 'json',
            contentType: 'application/json'
        }).done(function( data ) {
    });


回答7:

if you put {%csrf_token%} and still you have the same issue, please try to change your angular version. because its works for me. initially i faced this issue while using angular 1.4.x version . after i degrade it into angular 1.2.8, my problem was fixed. 
and dont forgot to add angular-cookies.js and put this on your js file.
if you using post request.
"app.run(function($http, $cookies) {
    console.log($cookies.csrftoken)
    $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
});
"


回答8:

In your HTML header, add

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

Then in your JS/angular config:

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