Error encountered during Django ajax POST: CSRF token missing or incorrect

i am facing an issue sending a csv file and a bunch of data through ajax. I keep getting a Forbidden (CSRF token missing or incorrect) error even though I am sending the csrftoken. One more thing, I noticed that I am getting a different token in the code and cookies. I have also checked the Django CSRF documentation but it didn't help. Can anyone please assist me with this?

Here is the JavaScript code:

$('#upload').click(function(){
    console.log('hello');
    var store = $('#id_store').val();
    var kitchen = $('#id_kitchen').val();
    var form = $('.csv').prop('files')[0];
    var csrftoken = $("[name=csrfmiddlewaretoken]").val();
    console.log(store)
    data={
     'csrfmiddlewaretoken':csrftoken,
     'kitchen':kitchen,
     'store':store,
     'csv_file':form,
     }
    console.log(data)
    $.ajax({
        url: "{{url('custom-admin:csv_upload')}}",
        type: 'POST',
        data: data,
         processData: false,
         contentType:false,
         success: function (data) {
           if(data.status){
            alert(data.message)
           }
           else{alert(data.message)}
    }
    });
    })

HTML File:

   <form id="demo-form2" method="post" data-parsley-validate="" class="form-horizontal form-label-left" enctype="multipart/form-data">
   <div class="form-group">
      <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
      <label class="control-label col-md-3 col-sm-3 col-xs-5"> Store <span
         class="required">*</span>
      </label>
      <div class="col-md-6 col-sm-6 col-xs-12 stores" id="stores">
         {{ form.store }}
      </div>
   </div>
   <div class="form-group">
      <label class="control-label col-md-3 col-sm-3 col-xs-5"> Kitchen <span
         class="required">*</span>
      </label>
      <div class="col-md-6 col-sm-6 col-xs-12 kitchen_list" id="kitchen_list">
         {{ form.kitchen }}
      </div>
   </div>
   <div class="form-group"  >
      <label class="control-label col-md-3 col-sm-3 col-xs-5" >  Upload File <span
         class="required"></span>
      </label>
      <div class="col-md-6 col-sm-6 col-xs-12 file">
         {{form.csv_file}}
         {% if form_errors.csv_file %}
         <div class="alert alert-danger">{{form_errors.csv_file}}</div>
         {% endif %}
      </div>
   </div>
   <div class="form-group" >
      <div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;">
         <button  type="button" class="btn btn-primary upload" id="upload"> Upload </button>
      </div>
   </div>
</form>

forms.py:

class CsvImportForm(forms.Form):
    kitchen = forms.ChoiceField(
        widget=forms.Select(attrs={
            'type': "radio",
            'class': "btn btn-primary btn-md",
            'data-parsley-multiple': 'gender'
        })
    )

    store = forms.ChoiceField(
        widget=forms.Select(attrs={
            'type': "radio",
            'class': "btn btn-primary btn-md stores",
            'data-parsley-multiple': 'gender'
        })
    )
    csv_file = forms.FileField(
        required=False,
        widget=forms.FileInput(attrs={
            'type': "file",
            'class':"csv",
            "data-validation": "mime",
            'data-validation-allowing': "csv",
            'data-validation-error-msg-mime': "You can only upload images in (csv)."
        })
    )

Answer №1

Give it a shot using the FormData function in javascript.

$('#upload').click(function(){  
        var formData = new FormData();
        var csrftoken = $("[name=csrfmiddlewaretoken]").val();
        formData.append('store', $('#id_store').val());
        formData.append('csrfmiddlewaretoken', csrftoken);
        formData.append('kitchen',  $('#id_kitchen').val());
        formData.append('csv_file', $('.csv')[0].files[0]);

    $.ajax({
        url: "{{url('custom-admin:csv_upload')}}",
        type: 'POST',
        data: formData,
        processData: false,
        contentType:false,
        success: function (data) {
           if(data.status){
            alert(data.message)
           }
           else{
            alert(data.message)
           }
        }
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error sending an email through the EmailJS backend JavaScript file

I am in the process of creating a route for my backend JavaScript Express server called server.js that will trigger an email to be sent to my Gmail account using EmailJS. When I attempt to use the following code: const SMTPClient = require("emailjs& ...

Creating Original Tweets using Javascript without Repeating Images

I'm developing a Twitter bot using the Twit NPM package and need assistance on how to avoid posting duplicate images when uploading images to Twitter. The current image_path variable is responsible for scanning through my image directory, but I want ...

Guide on inserting a new column into an array of objects in Vue

Below is the fetch method I have defined to retrieve recordings from the database. However, I need assistance in adding a new column to each record specifically for frontend purposes. Can someone help me with this problem? <script> export default { ...

What is the best way to apply a specific style based on the book ID or card ID when a click event occurs on a specific card in vue.js

My latest project involves creating a page that displays a variety of books, with the data being fetched from a backend API and presented as cards. Each book card features two button sections: the first section includes "ADD TO BAG" and "WISHLIST" buttons ...

Error: FullCalendar does not display a header for the timeGridWeek view when the dates fall

Currently, I am integrating fullcalendar 5.5.0 with Angular 10. After migrating from fullcalendar v4 to v5, I noticed an annoying issue where the header for the date before the validRange start is no longer displayed: https://i.sstatic.net/kvVUW.png Thes ...

Obtain identical encryption results with CryptoJS (JavaScript) and OpenSSL (PHP)

I am in the process of integrating a PHP encryption function into a ReactJS application. I have a requirement to transmit the token in a specific format that was generated using the OpenSSL library function (openssl_encrypt). It has been observed that the ...

Django 1.9.13 keeps giving a warning about the deprecation of SubfieldBase, even though I'm not utilizing it in my code. Any suggestions on

I am in the process of updating an outdated Django project from Django 1.8.3 to the latest Django 1.11 version. To ensure a smooth transition, I am incrementally upgrading to each major release of Django to catch any errors or deprecations and address them ...

Looking for a Plugin that Can Responsively Display Images in a Vertical Layout - Does One Exist using Jquery

Looking for a gallery slider plugin that is responsive both horizontally and vertically. Have tried Flexslider1/2, Galleria, and others but they do not adjust to vertical resizing. Changing the CSS did not help. If you resize the browser horizontally with ...

"Enhance your Vue components with a directive to customize or adjust element attributes

I have a variety of elements structured like this: <some-custom-component :errors="formErrors.has(getErrorKey('town'))" :error-messages="formErrors.getAll(getErrorKey('town'))" ></some-custom-component> The formErrors ...

Utilizing Discord.js to enable a command for a particular channel

Running a Discord.js bot and struggling to figure out how to restrict the command! help to only the #commands channel. Already have the channel ID, so what steps should be taken in the command event to achieve this? Appreciate any guidance! ...

What is the best way to implement a composite primary key in DocumentClient.batchWrite()?

I am attempting to conduct a batch delete process based on the instructions provided in this documentation. The example given is as follows: var params = { RequestItems: { /* required */ '<TableName>': [ { DeleteRequest: ...

Tips for using Angular's formatDate function to format dates

I am attempting to achieve a specific format using Angular's formatDate "2019-01-01T00:00:00Z" Here is the code I am using: formatDate( '2019-01-01', 'yyyy-MM-ddT00:00:00Z', 'en-US' ) The output I am getting is ...

Effective Ways to Utilize JOIN in Django ORM

login_key, location_key [30/Sep/2019 10:31:13] "POST /login/location_mapping HTTP/1.1" 500 142108 ...

Does the color of the item change as it gets older?

How can I smoothly transition a color as it ages using a dynamic time scale? I want to calculate the age based on the difference in time rather than triggering an animation after an event. I aim for a seamless gradient transition between two colors over a ...

How can I reverse the names displayed in ng-repeat when I click?

When utilizing the orderby filter in angularjs, I want to be able to sort the data only when the button is clicked. If the button is not clicked, the sorting order should not be displayed. <tr ng-repeat="tools in toolsfilter | orderBy:orderByField:reve ...

What steps can be taken to resolve webpage loading issues following data insertion into a database using express and node?

My express app has a post route handler (/addpost) for adding data to a database. Everything works perfectly, but the window keeps loading. To prevent the browser from waiting for more data, I know I need to send a response. However, all I want is for th ...

Conditionally render a div in React with Next.js depending on the value of a prop

Struggling with an issue in my app and seeking some guidance. The problem arises when dealing with data from contentful that has been passed as props to a component. Specifically, I only want to render a particular piece of data if it actually contains a v ...

Importing a 3D Model Using Three.js

I've been trying to import a 3D model by following tutorials. I managed to successfully import using A-Frame Tags, but encountering issues with Three.js. The code snippets are from a tutorial on YouTube that I referred to: https://www.youtube.com/watc ...

The appearance of the circle in Safari is rough and lacks smoothness

My circle animation works perfectly on Google Chrome, but when I switch to Safari the edges appear faded and blurry. I tried adding "webkit" to fix it, but had no luck. Is there a compatibility issue with Safari and CSS animations? Here is my code: Snapsh ...

Change the chart.js labels every time I make changes to the chart

I've been using chart.js to generate dynamic charts. While I can create different types of charts and manipulate the data displayed, I'm struggling with updating the labels. Below is my code snippet showcasing how I update the data: const color ...