Как добавить изображение для сериализации? - PullRequest
1 голос
/ 14 июня 2019

Как мне добавить image_form к form в Django?

form - form.serialize ()

image_form - image

$('#id_submit').click(function(e) {
  e.preventDefault();
  var form = $('form').serialize();
  image_form = $("#id_image")[0].files[0]

  var data = {
    form: form,
  }

  $.ajax({
    headers: {'X-CSRFToken': '{{ csrf_token }}' },
    type: 'POST',
    data: data,
  })
})

1 Ответ

2 голосов
/ 14 июня 2019

Вы можете попробовать как:

$('#id_submit').click(function(e) {
    e.preventDefault();
    var form = $('form').serialize();
    var image_form = $("#id_image").prop("files")[0];
    var data = new FormData(); // Creating object of FormData class
    data.append("form", form);
    data.append("image_form", image_form);
    $.ajax({
      headers: {'X-CSRFToken': '{{ csrf_token }}' },
      type: 'POST',
      data: data,
      //Options to tell JQuery not to process data or worry about content-type
      contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
      processData: false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
      cache: false, // To unable request pages to be cached
      success: function (res){}
   });
 }); 
...