How to send multiple forms with Ajax (FormData) in Django

How to send multiple forms with Ajax (FormData) in Django

How to send multiple forms with Ajax (FormData) in Django

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.

If you are a beginner, don’t worry we will go step by step through this tutorial. As always let’s create our Django project named mysite then create an app named core.

We are going to use images in our project, so we have to configure settings.py in order to serve static and media files and display templates. Update the TEMPLATES configuration like below:

Now, we should add static and media files configurations at the end of settings.py:

Well done! Next, we need to add models inside models.py. I will keep it as simple as possible so, the fields are title, description, and image for now:

models.py

Then, we need to migrate our models, so run the following commands in the console to make migrations:

Once it’s completed, open your views.py and we are going to create a very simple blog view just to show created posts for now:

views.py

then, we need to define a path in order to display our view in the browser so, update urls.py like below:

urls.py

Next, add a new folder named templates in the root level of the project to store our HTML files and inside it add two files named base.html and blog.html:

base.html

You can see two URLs inside the code snippet above one of them is for the blog and the second link is to create posts.

blog.html

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:

create-post.html

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:

views.py

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:

urls.py

That’s all! Now, you can run the Django server and check the functionality. It will look like below:

Django Server in Action

Django Server in Action

You can get the source code from my GitHub repository below:

https://github.com/raszidzie/django-ajax-formdata-tutorial

About the author

Stay Informed

It's important to keep up
with industry - subscribe!

Stay Informed

Looks good!
Please enter the correct name.
Please enter the correct email.
Looks good!

Related articles

19.10.2020

Automating and Scheduling Tasks Using Python

Python is an interpreted, high-level, cross-platform and easy-to-use programming language. Currently, it is one of the most powerful programming ...

Upload Multiple Images to a Django Model without plugins

In this article, I am going to show you how to add multiple images to a Django model without any plugins. It's better to keep the project simple and ...

How I Built an Admin Dashboard with Python Flask

In this article, I will share the how I built an admin dashboard. I will give a step by step guideline on how I built this application with Python ...

No comments yet

Sign in

Forgot password?

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy

Password recovery

You can also try to

Or use a social network account

 

By Signing In \ Signing Up, you agree to our privacy policy