CSRF verification failed. Request aborted

核能气质少年 提交于 2019-11-27 08:42:33
Burhan Khalid

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

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

    )

You may have missed adding the following to your form:

{% csrf_token %}

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.

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 ) {
    });

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');
}
Mohideen bin Mohammed

If you put {%csrf_token%} and still you have the same issue, please try to change your angular version. This worked for me. Initially I faced this issue while using angular 1.4.x version. After I degraded it into angular 1.2.8, my problem was fixed. Don't forget 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;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!