• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

How to Save Data from HTML Form to Database in Django?

Aniruddha Chaudhari/38121/32
Django

In an earlier tutorial, we learned to create your first Django application. In this tutorial, we are going to learn about creating Django form and storing data in the database.

The form is a graphical entity on the website where the user can submit their information. Later, this information can be saved in the database and can be used to perform some other logical operation.

As a part of this tutorial, we are going to create one HTML form where the user can enter their data. We will save this data into Django’s default SQLite database.

Steps to Save an HTML form and Insert Data to Database in Django

There are multiple steps involved. Let’s start one by one.

Table of Contents

  • Step 1. Creating a Model Class
  • Step 2. Understanding Different Model Field Types
  • Step 3. Making Migrations and Setting Database
  • Step 4. Create Form to Take the User Input
  • Step 5. Set URL and Run Django Application

Step 1. Creating a Model Class

A model is nothing but the source of information about the data where we can define the type of data, and behavior.

Usually, one model class maps to one database table.

You can find all the defined models in models.py file.

Open models.py and write a model class in it.

from django.db import models

class MyModel(models.Model):
    fullname = models.CharField(max_length=200)
    mobile_number = models.IntegerField()

Explanation:

  • In the first line of the code, we are importing models.
  • Create a new form (says MyForm) that is inherited from the models.Model class.
  • One-by-one you can define the form data/field with their data types.

In the above example, we have created two model data fields – CharField() and IntegerField().

Step 2. Understanding Different Model Field Types

There are different model field types you can use in the Django models. Most of these field types are self-descriptive.

Let’s check them one by one.

Field NameDescription
AutoFieldIt is an IntegerField that automatically increments for each entry.
BigAutoFieldIt can store values up to a 64-bit integer. This is also an automatically incremented field with a higher range of values.
BigIntegerFieldIt is similar to the IntegerField except that it is can store more values (up to 64-bit).
BinaryFieldIt is used to store binary data (zeros and ones).
BooleanFieldIt is a boolean field to store true or false.
By default, the checkbox form widget can be used.
CharFieldIt is used to store the set of characters (string). You can limit the number of characters.
DateFieldBasically, it is datetime.date instance. It can be used to store the date.
DateTimeFieldIt is used for date and time, represented in Python. It is a datetime.datetime instance.
DecimalFieldYou can save a fixed-precision decimal number, represented in Python. It is a Decimal instance.
DurationFieldThis field is used for storing periods of time (time span between two timestamps).
EmailFieldIt is an extension of CharField. It checks and stores only is a valid email address string. It throws an error if you try to store an invalid email address.
FileFieldThis field is used to upload the file.
FloatFieldIt is a floating-point number represented in Python by a float instance.
ImageFieldIt is an advanced version of FileUpload and inherits all attributes and methods from FileField. Apart from this, it also checks whether the uploaded object is a valid image or not. It only accepts a valid image.
IntegerFieldAs the name resonates, it is an integer field. It can accept values in a range of -2147483648 to 2147483647 (up to 32 bits).
GenericIPAddressFieldThis field accepts both the IPv4 or IPv6 addresses. It is actually a string that is a valid IP address. (difference between IPv4 and IPv6 address)
NullBooleanFieldIt is similar to the BooleanField. But, it also accepts NULL along with boolean values (True and False).
PositiveIntegerFieldThis field accepts positive integer values. (Note: It also accepts zero (0).
PositiveSmallIntegerFieldThis field accepts positive values (including zero (0)) in a certain range. The range of acceptance values depends on the database you are using.
SlugFieldSlug is a special string. which contains only letters, numbers, underscores, and hyphens. It is a short label. One of the examples of the slug is URL.
SmallIntegerFieldIt is similar to the PositiveSmallIntegerField as we have seen. But, it accepts both positive and negative values including zero (0).
TextFieldThis field is used to store a large text. For creating a form, we can use Textarea as a default form widget for TextField.
TimeFieldIt is a time field. It does not care about the date. In Python, it is an instance of datetime.time.
URLFieldIf you want to store the URL in the database, use this URL. The value in this field is validated by URLValidator.
UUIDFieldUUID is a universally unique identifier. This field accepts the UUID string.

Relationship Fields:

Django also defines a set of fields that represent relations between two data fields.

If you know the database, it has various keys used to map the relation. Similarly, we can define those relations using relationship fields in Django.

Field NameDescription
ForeignKeyThe foreign key represents many-to-one relationships. With the Foreign key, we can derive the key from the primary key of another model. For using ForeignKey two positional arguments are required- the class from where the key is derived and on_delete option (what should be the behavior if the primary key is deleted).
ManyToManyFieldIt maintains a many-to-many relationship. This field also requires positional arguments just like the Foreignkey field, including recursive and lazy relationships.
OneToOneFieldIt creates the one-to-one mapping between two model data.

Step 3. Making Migrations and Setting Database

After writing the Django model, you need to create the migrations. Run the following command to create the migrations.

python manage.py makemigrations

After running the command, you can see the migrations file created under the migrations folder. Something like this 0001_initial.py.

You are done with creating migrations. To reflect thing migrations into the database, you have to run the below command.

python manage.py migrate

You have applied migrations to the database successfully.

With this, you have created a backend.

Let’s create the front-end (form) to take the data from the user.

Step 4. Create Form to Take the User Input

Instead of creating HTML form manually, Django has an easy way of doing it.

First of all, create a new file as forms.py and write below Python code.

We are defining the form and attributes to display in the form.

from django import forms
from .models import MyModel

class MyForm(forms.ModelForm):
  class Meta:
    model = MyModel
    fields = ["fullname", "mobile_number",]
    labels = {'fullname': "Name", "mobile_number": "Mobile Number",}

Here are the things we are doing.

  • Inheriting forms.ModelForm class to create our own form.
  • In Meta class, we are defining the form attributes.
  • With the labels, we can customize form field labels to display.

Now create an HTML page template to display the Django form.

<div class="container">
    <form method="POST">
      <fieldset>
        <legend>Form</legend>
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-primary">Submit</button>
      </fieldset>
    </form>
</div>

Let’s save the file as cv-form.html in the templates directory.

Even if you know the basic HTML, you can understand the above HTML code.

You can also use bootstrap to customize the form and to make it look nice. I will show you that in the next tutorial. Now stick with this and continue with our tutorial to create an HTML form and insert data into the database using Django.

Let’s create a new function in views.py Python file.

from django.shortcuts import render
from .models import MyModel
from .forms import MyForm

def my_form(request):
  if request.method == "POST":
    form = MyForm(request.POST)
    if form.is_valid():
      form.save()
  else:
      form = MyForm()
  return render(request, 'cv-form.html', {'form': form})

This function will be called when the user hits the form URL in the web browser.

Step 5. Set URL and Run Django Application

Let’s call this form function by mapping it to the URL. Go to the urls.py and add the below line of code to urlpatterns the list.

url(r'form', views.my_form, name='form')

Now run and start the local server to test using the below command.

python manage.py runserver

It will start the local server. Now open localhost in a web browser.

Whenever a request comes to http://localhost:8000/form, it will call to the my_form() function defined in views.

Wow! You have created your first form. Submit the sample data in the form. The data will be saved in the database.

You can also see all the data submitted by the user in the Django admin dashboard. You have to register the model into the Django admin site.

In this tutorial, you have learned how to save data from html form to database in django.

Keep Learning!

Python Interview Questions eBook

Django
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    rene
    September 14, 2020 at 2:45 pm

    How do I find the model.py in my virtual environment project map…???

    • Reply
      Aniruddha Chaudhari
      September 16, 2020 at 8:36 pm

      Most probably you will find it inside the parent directory of the project. Otherwise, you can just do the file search.

  • Reply
    yogita
    October 12, 2020 at 3:10 pm

    Where you have created template directory?

    • Reply
      Aniruddha Chaudhari
      October 13, 2020 at 9:59 am

      Created a template directory inside the app directory. You can do the same.

  • Reply
    Sanvi
    May 20, 2021 at 10:02 pm

    How to get data from users like username password after submitting the login form and signup form?

    • Reply
      Aniruddha Chaudhari
      May 21, 2021 at 3:22 pm

      After submitting the form, data will be saved in the model. Check this tutorial to read the model data.

  • Reply
    anil
    June 1, 2021 at 10:39 am

    Why do we use forms? We can normally give it to the models and add it to the views.py?

    • Reply
      Aniruddha Chaudhari
      June 1, 2021 at 12:59 pm

      There are a lot of things you can do with the forms. You can make the forms independent of models. It means you can create forms without a model. You can also add additional fields in the forms which does not require models. This is a good programming practice to adopt in the project development.

  • Reply
    Jagannath Bhanja
    July 6, 2021 at 2:54 pm

    Where you have created forms.py?

    • Reply
      Aniruddha Chaudhari
      July 8, 2021 at 3:19 pm

      It is in the app directory where models.py or views.py present.

  • Reply
    Aakash Gupta
    July 16, 2021 at 12:43 am

    If we want to store multiple values for a single instance how can we do it? And the number of values will be different. For eg, if a salon registers its services on a site, the number of services provided by different salons will be different. So how we can store all services in SQLite database for a particular salon.

    • Reply
      Aniruddha Chaudhari
      July 22, 2021 at 8:18 pm

      Akash, you need to create two database tables in the case of a relational database system. Create one table (with name, says, Salon) that store detail about each Salon. Create another table (with name, says, Services) that store detail about each service. There will be one foreign key in the Services table derived from the primary key of the Salon table. You can read more about the foreign key concept here.

  • Reply
    peter
    August 10, 2021 at 5:25 pm

    Halo, thanks for this tutorial. Now my question is how do I decorate the form fields so that they are spaced nicely, because as for now there is no spacing between the fields.

    • Reply
      Aniruddha Chaudhari
      September 14, 2021 at 9:14 am

      There are multiple solutions to accomplish this. Here are two ways.

      1. Simple solution is to use form.as_table over form.as_p in the Django template. It puts each field in the new cell with some spacing. You can also adds some CSS.
      2. If you want more control over each field, you can render each field manually using render.

      {% render_field form.field_name class="form-control" %}
  • Reply
    Abhishek Kumar Prajapati
    November 11, 2021 at 10:59 am

    In my case, all the fields username and mobile number are very close to each other. Also, I want to add a box for a message on how can I set it. Also, can you tell me how csrf_token works

    • Reply
      Aniruddha Chaudhari
      January 29, 2022 at 11:40 am

      1.”all the fields username and mobile number are very close to each other.”
      – add some padding or margin in your HTML CSS code.

      2. “I want to add a box for a message”
      – Use TextField() in Django.

      3. “tell me how csrf_token works”
      – Basically, the CSRF token is a value field in Django model form, just to ensure, the POST request or form is submitted by the valid user from the trusted domain. There is a separate token created for each session user so that only that user can submit the form. Not sending or sending invalid CSRF token, Django does not accept the form submission considering it is coming from not trusted domain.

  • Reply
    Anuragav
    June 14, 2022 at 12:39 am

    I have pasted the URL at the bottom line of urlpattern but I get NameError: name ‘url’ is not defined
    error what do I do???

    • Reply
      Aniruddha Chaudhari
      June 23, 2022 at 11:24 pm

      Looks like you have missed to import url.
      Add the below line at the nbegineing of the file.

      from django.conf.urls import url

      It will solve your problem.

  • Reply
    Musa Adamu
    July 31, 2022 at 9:45 pm

    Good day. I have followed the tutorial and have been able to get the form but when I clicked on the submit button, data is not added to my model table. I am using postgresql and pgadmin to view the models and the table values. My model is visible and created but data failed to be added. Thank you.

    • Reply
      Aniruddha Chaudhari
      August 1, 2022 at 9:34 am

      Hi Musa, very difficult to identify the issue with the information you provided. Couple of questions to trace the bug. Did you see any errors on the console? If so, it will reflect the actual issue. You can share that error message. If there is no error on the console, add multiple debugging statements/prints to check if everything is working as expected.

      • Reply
        Musa Adamu
        August 6, 2022 at 4:41 pm

        Thank you for the reply. I am able to have the data added to the database table but one thing I noticed with the mobile number is that it does not take more than ten numbers. How do I increase that? Thank you.

        • Reply
          Aniruddha Chaudhari
          August 8, 2022 at 9:55 am

          You’re welcome, Musa! And I’m glad your previous issue is resolved.

          Use IntegerField() to store the mobile number in the Django model.

          Example: mobile = models.IntegerField(blank=True, null=True)

          It allows you to save 10 digits mobile numbers.

          • Musa Adamu
            August 9, 2022 at 12:05 am

            Thank your sir. I wanted to save more than ten digits because, in the example above, it provided for only ten digits. Thank you.

            Please, I don’t know if you can help with this problem too.

            I have created a model in my database and wanted to implement an example in a tutorial I watched but the new users are not added to the database table. below is the code in views.py

            from django.shortcuts import render, redirect
            from formRegister.models import FormRegister
            
            # Create your views here.
            
            def register(request):
                
                if request.method == 'post':
                    
                    first_name = request.POST['fisrt_name']
                    last_name = request.POST['last_name']
                    username = request.POST['username']
                    
                                  
                    user = FormRegister.objects.create_user(username=username, first_name=first_name, last_name=last_name)
                    user.save(commit = True);
                   
                    return redirect('/')
                else:
                    return render (request, 'formRegister.html')
            

            I want to implement the above example where you create your form on a separate HTML page and add it to the model as above but I couldn’t achieve that despite implementing all that is required.

            I notice when I write FormRegister.objects.create_user, at FormRegister. objects come up but after objects. create_user does not come up. I don’t know whether the create_user used in the tutorial has been deprecated or not in use. Thank you. I have successfully implemented the form type in your tutorial but just trying to have a variety.

          • Aniruddha Chaudhari
            August 18, 2022 at 9:58 am

            Hi Musa, I wonder why are you using create_user when you can simply read the Django form and save it in the model DB as shown in the above tutorial. It is simple and easy. I think you should try that. And let me know if it does not work.

  • Reply
    Ginto
    August 13, 2022 at 5:11 pm

    If i have a select tag that contain many options (can only select one option) then how i store data to database, what will be the datafield for that is textfield?

    • Reply
      Aniruddha Chaudhari
      August 18, 2022 at 9:45 am

      If you want to allow a user to select only a single tag, you can use a drop-down list if all the tag options are known. In the case of multiple tags selection, you can check the input tags. In both cases, the model field will be TextField and CharField as Django form field.

    • Reply
      Musa Adamu
      August 19, 2022 at 5:36 pm

      I am following a tutorial and have seen how the create user was implemented and that is why I want to do the same. I have successfully implemented the above tutorial and it worked quite alright.

      • Reply
        Aniruddha Chaudhari
        August 25, 2022 at 10:28 pm

        Great, Musa! I’m glad you find my tutorial useful. Hope you enjoy going through my other Django tutorials as well.

  • Reply
    Nikita
    August 29, 2022 at 2:11 pm

    Hi,

    I have a form where the user inputs some text. I need to write a code to insert that text into the database column in the backend once the user hits submit button for the ID present in the URL.

    • Reply
      Aniruddha Chaudhari
      August 31, 2022 at 11:14 pm

      Hi Nikita,

      I have already explained this. Please check this tutorial.

  • Reply
    Ata Ur Rehman
    November 10, 2022 at 10:09 pm

    sir

    After Submitting how to get save data from model.py for login page in django

    • Reply
      Aniruddha Chaudhari
      December 8, 2022 at 11:30 pm

      You can just query the request to read the data from the model using Django ORM.

Leave a Reply Cancel reply

Prerequisite for Django

Learn Python Basics

Django Tutorials

Why Django?

Django- Create Your First Project

Django- Adding CSS/Static Files

Django- Use/Load Static Files

Django- Create Form

Django- Create Input-Tags

Django- Display Message on Form Submit

Django- MultipleChoiceField in Form

Django- Read Model Data (order_by)

Django- Read First/Last Queryset Object

Django- Update Model Field

Django- Signals

Django- Create TextField in Form

Django- Add Model to Admin Site

Django- Customize Admin Site

Django- Understanding Model User

Django- Registration/Signup Form

Django- Form Layout with Widget-Tweaks

Django- OneToOneField in Model

Django- Foreign Key & Reverse Lookup

Django- Custom Template Filters

Django- Interactive Shell

Django- Social Login

Django- Deploy and Host [FREE] 🔥

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard