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

How to Save Data from HTML Form to Database in 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.

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 Name Description
AutoField It is an IntegerField that automatically increments for each entry.
BigAutoField It can store values up to a 64-bit integer. This is also an automatically incremented field with a higher range of values.
BigIntegerField It is similar to the IntegerField except that it is can store more values (up to 64-bit).
BinaryField It is used to store binary data (zeros and ones).
BooleanField It is a boolean field to store true or false.
By default, the checkbox form widget can be used.
CharField It is used to store the set of characters (string). You can limit the number of characters.
DateField Basically, it is datetime.date instance. It can be used to store the date.
DateTimeField It is used for date and time, represented in Python. It is a datetime.datetime instance.
DecimalField You can save a fixed-precision decimal number, represented in Python. It is a Decimal instance.
DurationField This field is used for storing periods of time (time span between two timestamps).
EmailField It 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.
FileField This field is used to upload the file.
FloatField It is a floating-point number represented in Python by a float instance.
ImageField It 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.
IntegerField As the name resonates, it is an integer field. It can accept values in a range of -2147483648 to 2147483647 (up to 32 bits).
GenericIPAddressField This 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)
NullBooleanField It is similar to the BooleanField. But, it also accepts NULL along with boolean values (True and False).
PositiveIntegerField This field accepts positive integer values. (Note: It also accepts zero (0).
PositiveSmallIntegerField This field accepts positive values (including zero (0)) in a certain range. The range of acceptance values depends on the database you are using.
SlugField Slug 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.
SmallIntegerField It is similar to the PositiveSmallIntegerField as we have seen. But, it accepts both positive and negative values including zero (0).
TextField This field is used to store a large text. For creating a form, we can use Textarea as a default form widget for TextField.
TimeField It is a time field. It does not care about the date. In Python, it is an instance of datetime.time.
URLField If you want to store the URL in the database, use this URL. The value in this field is validated by URLValidator.
UUIDField UUID 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 Name Description
ForeignKey The 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).
ManyToManyField It maintains a many-to-many relationship. This field also requires positional arguments just like the Foreignkey field, including recursive and lazy relationships.
OneToOneField It 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!

37 Comments

    1. I am wondering, I want to save information that is from a drop down list and radio button. Which model fields in Django do I use?

    1. 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.

  1. 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.

    1. 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.

  2. 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.

    1. 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" %}
  3. 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

    1. 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.

  4. 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???

  5. 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.

    1. 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.

      1. 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.

        1. 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.

          1. 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.

          2. 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.

  6. 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?

    1. 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.

    2. 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.

  7. 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.

Leave a Reply

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