禁止(CSRF令牌丢失或不正确。):/ u / submit

时间:2018-07-22 15:37:28

标签: python ajax django

views.py

def form(request):
    if request.method == 'POST':
        form = StudentForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse('done')
    else:
        form = StudentForm()
    return render(request,'submit.html',{'form':form})

urls.py

urlpatterns = [
    path('submit',views.form, name = 'submit')
]

templates / html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
   </script>

    <script src="{% static 'js/ajax2.js' %}" type="text/javascript"></script>
</head>


<body>

<form class="form_ajax" method="post" data-url="/submit" >
    {% csrf_token %}
    {{ form }}
    <button id="btn" type="submit">Submit</button>
</form>
</body>

ajax2.js

$(document).ready(function(){
    $('#btn').click(function(event){
        event.preventDefault()
        var name = $('#id_name').val();
        var marks = $('#id_marks').val();
        var year = $('#id_year').val();
        csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()

        $.ajax({
            url :'/u/submit',
            type: 'POST',
            data :{'name':name,'marks':marks,'year':year},
            success : function(data){
                console.log(data);
                alert('created:',data);
            },
        });
    });
});

它显示Forbidden (CSRF token missing or incorrect.): /u/submit。因此我试图用不同的方法来做js

$(document).ready(function(){
    $('#btn').click(function(event){
        event.preventDefault()
        var myForm = $('.ajax_form');
        var formData = myForm.serialize();
        var thisUrl = myForm.attr('data-url') || window.location.href;



        $.ajax({
            url :thisUrl,
            type: 'POST',
            data :formData,
            success : function(data){
                console.log(data);
                alert('created:',data);
            },
        });
    });
});

但是它播出了相同的403错误,但是您可以看到我以html形式给出了csrf_token。但是仍然给出了错误。即使在ajax中提供csrf中间件令牌,它现在仍然可以正常工作。做错了吗?

1 个答案:

答案 0 :(得分:0)

在您的jquery ajax调用中添加csrf令牌标头,如下所示:

$(document).ready(function(){
    $('#btn').click(function(event){
        event.preventDefault()
        var myForm = $('.ajax_form');
        var formData = myForm.serialize();
        var thisUrl = myForm.attr('data-url') || window.location.href;

       let csrfcookie = function() {
            let cookieValue = null,
                name = "csrftoken";
            if (document.cookie && document.cookie !== "") {
                let cookies = document.cookie.split(";");
                for (let i = 0; i < cookies.length; i++) {
                    let cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) == (name + "=")) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        };

        $.ajax({
            url :thisUrl,
            type: 'POST',
            beforeSend: function(request, settings) {
                        if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                            request.setRequestHeader("X-CSRFToken", csrfcookie());
                        }
                    },
            data :formData,
            success : function(data){
                console.log(data);
                alert('created:',data);
            },
        });
    });
});