How to send multiple forms with FormData and jQuery ajax in Django by Rashid Maharamli

Introduction

In this article, I am going to show you how to send multiple forms in Django using Ajax and FormData .

Normally, it’s also possible to send forms only with Ajax by defining data inside the function.

However, with FormData it becomes much simpler and faster to handle the form submission.

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField()
    image = models.FileField(blank=True)

    def __str__(self):
        return self.title
{% block content %}
<form>
    <div class="form-group">
      <label>Title</label>
      <input type="text" class="form-control" id="title" placeholder="Enter title">
    </div>
    <div class="form-group">
      <label>Description</label>
      <textarea id="description" class="form-control" placeholder="Enter description"></textarea>
    </div>
    <div class="form-group">
        <label>Upload Image</label>
        <input type="file" id="image" class="form-control-file">
    </div>
    <button type="button" id="submit" class="btn btn-primary">Submit</button>
  </form>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    var formData = new FormData();

      $(document).on('click', '#submit', function(e) {
        formData.append('title', $('#title').val())
        formData.append('description', $('#description').val())
        formData.append('image',  $('#image')[0].files[0])
        formData.append('action', 'create-post')
        formData.append('csrfmiddlewaretoken', '{{ csrf_token }}')
          $.ajax({
              type: 'POST',
              url: '{% url "create-post" %}',
              data: formData,
              cache: false,
              processData: false,
              contentType: false,
              enctype: 'multipart/form-data',
              success: function (){
                  alert('The post has been created!')
              },
              error: function(xhr, errmsg, err) {
                  console.log(xhr.status + ":" + xhr.responseText)
              }
          })
      })
</script>
{% endblock %}

So, the blog template is ready to display all posts and it’s time to add a new function to handle post creation.

FormData and AJAX

FormData is basically a data structure that can be used to store key-value pairs.

It’s designed for holding forms data and you can use it with JavaScript to build an object that corresponds to an HTML form.

In our case, we will store our form values and pass them into ajax, and then ajax will make a POST request to Django back-end.

Now, create a new HTML file named create-post.html in the templates directory and add the following code snippet below:

{% block content %}
<form>
    <div class="form-group">
      <label>Title</label>
      <input type="text" class="form-control" id="title" placeholder="Enter title">
    </div>
    <div class="form-group">
      <label>Description</label>
      <textarea id="description" class="form-control" placeholder="Enter description"></textarea>
    </div>
    <div class="form-group">
        <label>Upload Image</label>
        <input type="file" id="image" class="form-control-file">
    </div>
    <button type="button" id="submit" class="btn btn-primary">Submit</button>
  </form>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    var formData = new FormData();

      $(document).on('click', '#submit', function(e) {
        formData.append('title', $('#title').val())
        formData.append('description', $('#description').val())
        formData.append('image',  $('#image')[0].files[0])
        formData.append('action', 'create-post')
        formData.append('csrfmiddlewaretoken', '{{ csrf_token }}')
          $.ajax({
              type: 'POST',
              url: '{% url "create-post" %}',
              data: formData,
              cache: false,
              processData: false,
              contentType: false,
              enctype: 'multipart/form-data',
              success: function (){
                  alert('The post has been created!')
              },
              error: function(xhr, errmsg, err) {
                  console.log(xhr.status + ":" + xhr.responseText)
              }
          })
      })
</script>
{% endblock %}

As you can see in the <script> part, first we are creating a FormData object and then using append() method to append a key-value pair to the object.

You can change the key name whatever you want but I am keeping it the same as the field names because we will use them later to fetch data in Django views.

You can see I am using the field id to get the right fields and the values are fetched by using val() method.

The image is file input so we can’t get the file just using val() method.

The file input stores list of files and since we are uploading only one file, we can get it from the first position of the list.

At the beginning of this tutorial, we said that we want to send multiple forms from a single view, and to achieve that we must define an extra field just to separate POST requests in the back-end.

I created a new key-value pair named action and the value is create-post.

Once a POST request has been sent to the views, it will fetch the action field, and if its create-post then a new object will be created. You can add how many forms you want but keep in mind that you have to define an extra field to separate these forms.

Finally, we appended csrfmiddlewaretoken to avoid 403 forbidden when the POST request has been made.

In the ajax function, instead of defining each filed manually, we are passing FormData directly into the data property.

It’s imperative to set the contentType option to false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it.

Also, you must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.

Because we are sending images the enctype must be ‘multipart/form-data’ so our image file will be encoded.

Great! Now, let’s switch to our views.py and fetch all these data in order to create a new post object:

from django.shortcuts import render
from .models import Post

def blog_view(request):
    posts = Post.objects.all().order_by('-id')
    return render(request, 'blog.html', {'posts':posts})

def create_post_view(request):
    if request.POST.get('action') == 'create-post':
        title = request.POST.get('title')
        description = request.POST.get('description')
        image = request.FILES.get('image') # request.FILES used for to get files

        Post.objects.create(
            title=title,
            description=description,
            image=image
        )

    return render(request, 'create-post.html')

Simply, we are getting the data by its key name and then using in create() method to create a new object in the database.

As you see in the if statement we checked the action name, so if the action name is create-post then the object will be created.

Finally, let’s update urls.py by adding a new path:

from django.urls import path
from django.conf import settings
from django.conf.urls.static import static

from core.views import blog_view, create_post_view
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', blog_view, name='blog'),
    path('create-post/',create_post_view, name='create-post')

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)