How to save form data in database in django

Hello World, Welcome to Today we will learn how to save form data in the database in django. We will use the SQL database. I am assuming that you have installed Django in your system, If not then please refer to this tutorial. We will create a simple contact form in which the user will fill his basic information like full name, email, and message.
I have divided this tutorial into the following parts.

  • Create a contact model
  • Create contact form template
  • Submit form and save data in the database

Create a contact model

In this step, we will create a contact model in which we will save data.

  • Open the in your app
  • Add the following Contact class in this file.
class Contact(models.Model):

    def __str__(self):
        return self.full_name
  • Run the following commands to apply migrations
  • py makemigrations
  • py migrate

Create contact form template

Create templates folder in your app directory and create contact.html file in this templates folder. Add the following code in this file.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Form</title>
    <h3>Contact Form</h3>
    <form method="post" action="/contact-form">
        {% if messages %}
            {% for msg in messages %}
            {% endfor %}
        {% endif %}
        {% csrf_token %}
        <table border="1" cellpadding="5">
                <th>Full Name</th>
                <td><input type="text" name="full_name" /></td>
                <td><input type="email" name="email" /></td>
                    <textarea name="message"></textarea>
                <td colspan="2"><input type="submit" value="Submit" /></td>

Submit form and save data in the database

Add the following code in file.

def contact(request):
    if request.method=='POST':
        messages.success(request,'Data has been submitted')
    return render(request,'contact.html')

The above code will verify the request method and save the data in Contact Model.

Please add the following code in your-app/


Start the server and run your project. You will see the following screen.

Leave a Reply

Your email address will not be published. Required fields are marked *