使用具有 action 属性的多个 post 方法时出现错误 403 csrf 令牌

error 403 csrf token when using multiple post method with action attribute

我得到一个页面如何有多个 POST 方法,所以我使用 ajax 中的 action 属性来识别每个 post 方法,但是当我尝试使用它时在如何将模型添加到数据库(客户端模型)的表单上,它说 403 错误无效或缺少 csrf 令牌,但是当我删除操作并只让 REQUEST.METHOD == 'POST' 时,它起作用了,所以我不明白为什么 csrf 令牌在我使用该操作时不起作用,我通过直接获取输入表单的值解决了这个问题,但如果我使用 django 表单的自动化功能会更好,所以它们是我的旧代码。

ajax 请求:

$(document).ready(function(){

var csrfToken = $("input[name=csrfmiddlewaretoken]").val();
//$("#alert-container").hide();
    //console.log(csrfToken);

$("#btn-submit").click(function() {
    var serializedData = $("#ClientForm").serialize();
    console.log("hey hey clients!");
    $.ajax({ 
               url: $("ClientForm").data('url'),
               data :{serializedData,action: 'client'},
               type: 'post',
              
               success: function(response) {
                    console.log(response.client.name);
                    console.log($("#ClientList"))
                    
                    
               }
           })
    $("#ClientForm")[0].reset()
});

});

html 形式 :

 <form class="contact-form" id="ClientForm" data-url="{% url 'addclient' %}" method="POST">

                            {% csrf_token %}
                            <div class="form-group">
                                <label for="name" class="sr-only">Name</label>
                                {{ form.name }}
                            </div>
                            <div class="form-group">
                                <label for="email" class="sr-only">Email</label>
                                {{ form.email }}
                            </div>
                            
                            <div class="form-group">
                                <button type="button"  id="btn-submit" class="btn btn-success btn-md">Add Client </client>
                                
                                
                            </div>
</form>

View.py:

def addclient(request):
form = ClientForm()
clients = client.objects.filter(affiliation=request.user.id)
Csession = session.objects.filter(coach=request.user.id)

context = {'form': form ,'clients': clients , 'Csession' : Csession}

#form = ClientForm
if request.method == 'POST' and request.POST['action'] == 'client':
    form = ClientForm(request.POST)
    print(form)
    name = request.POST.get('name')
    email = request.POST.get('email')
    new_client = client.objects.create(name = name, email = email, affiliation = request.user)
    new_client.save()
    return JsonResponse({'client': model_to_dict(new_client)}, status=200)
    
    #commment for the old code
    '''if form.is_valid():
        print('adding client 1133 to the hell', form)
        name = request.POST.get('name')
        email = request.POST.get('email')
        new_client = client.objects.create(name= name, email=email , affiliation=request.user)
        new_client.save()
        return JsonResponse({'client': model_to_dict(new_client)}, status=200)

    else:
        print('not adding client to the form 1333 dahell')

        return redirect('addclient')'''


        #return JsonResponse({'session': model_to_dict(Sclient)}, status=200)
else:
    print('not adding task')
    #return redirect('addclient')

工作Ajax代码:

$(document).ready(function(){

var csrfToken = $("input[name=csrfmiddlewaretoken]").val();
$("#alert-container").hide();
    //console.log(csrfToken);

$("#btn-submit").click(function() {
    var serializedData = $("#ClientForm").serialize();
    var data1 = $("input[name=name]").val();
    var data2 = $("input[name=email]").val();
    console.log("hey hey clients!");
    $.ajax({ 
               url: $("ClientForm").data('url'),
               data : {
                        csrfmiddlewaretoken: csrfToken,
                        //serializedData,
                        name : data1,
                        email : data2,
                        action: 'client'
                      },
               type: 'post',
              
               success: function(response) {
                    console.log(response.client.name);
                    console.log($("#ClientList"))
                    //var block ='<div class="heading-section animate-box"> <h2>Client </h2> </div> </div> <div class="col-md-12"> <div class="fh5co-blog animate-box"> <div class="inner-post"> <a href="#"><img class="img-responsive" src="images/user.jpg" alt=""><i class="fa fa-user fa-5x" style="margin: 20px;"></i></a> </div> <div class="desc" style="padding-bottom: 2rem;"> <span class="posted_by"></span> <span class="comment"></a></span> <h3>'+ response.client.name +'</h3> <h3>'+ response.client.email +'</h3>  <a href="addexercise.html" class="btn btn-success" style="margin-bottom: 1rem; margin-right: 2rem;">Add / Edit Exercises</a></div> <a href="client.html" class="btn btn-warning" style="margin-bottom: 1rem;">View</a> </div> '
                    //var test = '<h2>'+ response.client.name +'</h2>'
                    var test2 = document.createElement('div');
                    test2.innerHTML = '<div class="list-group list-group-me"> <ul class="list-group list-group-horizontal"> <li class="list-group-item">'+ response.client.name +'</li>  <li class="list-group-item">'+ response.client.email +'</li> <li class="list-group-item"> Today </li> <li class="list-group-item list-group-item-warning">Inactive</li> <li class="list-group-item">025f55azg5</li>  <button type="button" class="btn btn-outline-info">Client Not Active</button> </ul> </div>'
                    //var card = '<div class="card mt-2" id="taskCard" data-id="'+response.client.id+'"><div class="card-body" >'+ response.client.name +'<button type="button" class="close float-right" data-id="'+response.client.id+'" > <span aria-hidden="true">&times;</span></button></div></div>'
                    //$(block).appendTo("#clientList")
                    //$("#clientList").append(card).html();
                    document.getElementById("clientList").appendChild(test2)
                    //'<div class="col-md-12" id="clientList"><div class="col-md-12"><div class="heading-section animate-box"><h2>Client</h2></div></div> <div class="col-md-12"><div class="fh5co-blog animate-box"><div class="inner-post"><a href="#"><img class="img-responsive" src="images/user.jpg" alt=""><i class="fa fa-user fa-5x" style="margin: 20px;"></i></a></div><div class="desc" style="padding-bottom: 4rem;"><span class="posted_by"></span><span class="comment"></a></span><h3>Yoww</h3><a href="addexercise.html" class="btn btn-success" style="margin-bottom: 1rem; margin-right: 2rem;">Add / Edit Exercises</a><a href="client.html" class="btn btn-warning" style="margin-bottom: 1rem;">View</a></div> </div> </div>'
               }
           })
    $("#ClientForm")[0].reset()
});

所以我希望你能帮助我,我不明白为什么我在使用 action 属性时遇到这个问题。

猜测解决方案。您可以尝试下面的 ajax 调用,看看它是否有效。

$(document).ready(function(){

var csrfToken = $("input[name=csrfmiddlewaretoken]").val();
//$("#alert-container").hide();
    //console.log(csrfToken);

$("#btn-submit").click(function() {
    var serializedData = $("#ClientForm").serializeArray();
    serializedData.push({name:'action',value:'client'})
    serializedData.push({name: 'csrfmiddlewaretoken', value: csrfToken})
    console.log("hey hey clients!");
    $.ajax({ 
               url: $("ClientForm").data('url'),
               data : serializedData,
               type: 'post',
              
               success: function(response) {
                    console.log(response.client.name);
                    console.log($("#ClientList"))
                    
                    
               }
           })
    $("#ClientForm")[0].reset()
});