CSRF verification failed. Request aborted

后端 未结 10 1878
执笔经年
执笔经年 2020-12-01 13:04

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         


        
相关标签:
10条回答
  • 2020-12-01 13:17

    USE decorator:

    from django.views.decorators.csrf import csrf_exempt
    
    @csrf_exempt
    def method_name():
        # body
    
    0 讨论(0)
  • 2020-12-01 13:18

    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;
    });
    
    0 讨论(0)
  • 2020-12-01 13:20

    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.

    0 讨论(0)
  • 2020-12-01 13:21

    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})
    
    0 讨论(0)
  • 2020-12-01 13:23

    You may have missed adding the following to your form:

    {% csrf_token %}
    
    0 讨论(0)
  • 2020-12-01 13:23
    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 ) {
        });
    
    0 讨论(0)
提交回复
热议问题