E
E
Egor2018-10-02 17:45:44
Django
Egor, 2018-10-02 17:45:44

How to send files with AJAX in Django?

For example, to pass a regular text field, I do this:

var text = $('#form-new-task-z-r-text').val(); 

jQuery.ajax({
  type: 'POST',
  url: 'add_new_rec/'+prot_id+'/'+id_q+'/',
  data: {csrfmiddlewaretoken: getCookie('csrftoken'), 'r_text':text},
       success: function(data) {
       }
});


Send files advised like this:
var text = $('#form-new-task-z-r-text').val(); 
var my_file = $('#file_record').prop('files');

$.ajax({
               type: 'POST',
                url: 'add_new_rec/'+prot_id+'/'+id_q+'/',
                async: true,
                cache: false,
                processData: false,
                contentType: false,
                enctype: 'multipart/form-data',
                data: {csrfmiddlewaretoken: getCookie('csrftoken'), 'r_text':text, 'file':my_file},
                  success: function(data) {
                   //...

With this example, both the text and the file are not sent. Writes 403 error. I need to transfer files and text at the same time.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question