Fabe
Fabe

Reputation: 759

Django File missing when upload with ajax

I work on project django (V2.1 + python 3.6) upload text files. I have a template for the files I want to upload except that when the form is sent the file is missing; I do not know what's wrong.

That's my models:

from django.db import models

class Document(models.Model):
    description = models.CharField(max_length=255, blank=True)
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

That's my template:

<form enctype="multipart/form-data" method="post" action="{% url 'add_document' %}" class="js-add-document-form">
  {% csrf_token %}
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
    <h4 class="modal-title">Add document</h4>
  </div>
  <div class="modal-body">
    {% include 'books/includes/partial_doc_form.html' %}
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">ADD</button>
  </div>
</form>

That's my view:

def save_doc_form(request, form, template_name):
    data = dict()
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
            docs = Document.objects.all()
            data['html_doc_list'] = render_to_string('docs/includes/partial_docs_list.html', {
                'docs': docs
            })
        else:
            data['form_is_valid'] = False
    context = {'form': form}
    data['html_form'] = render_to_string(template_name, context, request=request)
    return JsonResponse(data)


def doc_create(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
    else:
        form = DocumentForm()
    return save_book_form(request, form, 'docss/includes/partial_docs_create.html')

That's my js file:

$(function () {
  /* Functions */
  var loadForm = function () {
    var btn = $(this);
    $.ajax({
      url: btn.attr("data-url"),
      type: 'get',
      dataType: 'json',
      beforeSend: function () {
        $("#modal-doc").modal("show");
      },
      success: function (data) {
        $("#modal-doc .modal-content").html(data.html_form);
      }
    });
  };
  var saveForm = function () {
    var form = $(this);
    $.ajax({
      url: form.attr("action"),
      data: form.serialize(),
      type: form.attr("method"),
      dataType: 'json',
      success: function (data) {
        if (data.form_is_valid) {
          $("#doc-table tbody").html(data.html_docs_list);
          $("#modal-doc").modal("hide");
        }
        else {
          $("#modal-doc .modal-content").html(data.html_form);
        }
      }
    });
    return false;
  };
  /* Binding */
  // Create document
  $(".js-add-document").click(loadForm);
  $("#modal-doc").on("submit", ".js-add-document-form", saveForm);
});

Everything seems to work fine except that when the form is sent, it does not contain any file. Example: When i doing something like:

print('----->>>>', form.cleaned_data['document']) I get None. Please help ! i don't know what i wrong.

Upvotes: 3

Views: 899

Answers (2)

Fabe
Fabe

Reputation: 759

After many search with litte help of @Hayden i finish to find solution:

My Upload js with formData:

$(function () {
  /* Functions */
  /** No change to LodForm **/

  var saveForm = function () {
    var form = $(this);
    var formData = new FormData(form[0]);
    $.ajax({
      url: form.attr("action"),
      data: formData,
      type: form.attr("method"),
      dataType: 'json',
      async: true,
      cache: false,
      contentType: false,
      enctype: form.attr("enctype"),
      processData: false,
      success: function (data) {
        if (data.form_is_valid) {
          $("#doc-table tbody").html(data.html_docs_list);
          $("#modal-doc").modal("hide");
        }
        else {
          $("#modal-doc .modal-content").html(data.html_form);
        }
      }
    });
    return false;
  };
  /* Binding */
  // Create document
  $(".js-add-document").click(loadForm);
  $("#modal-doc").on("submit", ".js-add-document-form", saveForm);
});

It work like a charm, But many others solutions exist like in this page

Upvotes: 2

Hayden
Hayden

Reputation: 459

The jQuery form.serialize() function can't encode multipart body, I recommend FormData API

Upvotes: 1

Related Questions