How to create an HTML form and insert data into the database using Django?
In an earlier tutorial, we have learned to create your first Django application. In this tutorial, we are going to learn about creating Django form and storing data into 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.
Create an HTML form and Insert Data into the Database using Django
There are multiple steps involved. Let’s start one-by-one.
Table of Contents
Step 1. Creating a Model Class
Model is nothing but the source of information about the data where we can define the type of data, 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-on 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 the 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 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 to create an HTML form and insert data into the database using Django.
Keep Learning!
Comments
rene
How do I find the model.py in my virtual environment project map…???
Aniruddha Chaudhari
Most probably you will find it inside the parent directory of the project. Otherwise, you can just do the file search.
yogita
Where you have created template directory?
Aniruddha Chaudhari
Created a template directory inside the app directory. You can do the same.
Sanvi
How to get data from users like username password after submitting the login form and signup form?
Aniruddha Chaudhari
After submitting the form, data will be saved in the model. Check this tutorial to read the model data.
anil
Why do we use forms? We can normally give it to the models and add it to the views.py?
Aniruddha Chaudhari
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.
Jagannath Bhanja
Where you have created forms.py?
Aniruddha Chaudhari
It is in the app directory where
models.py
orviews.py
present.Aakash Gupta
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.
Aniruddha Chaudhari
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.
peter
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.
Aniruddha Chaudhari
There are multiple solutions to accomplish this. Here are two ways.
1. Simple solution is to use
form.as_table
overform.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.
Abhishek Kumar Prajapati
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
Aniruddha Chaudhari
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.
Anuragav
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???
Aniruddha Chaudhari
Looks like you have missed to import url.
Add the below line at the nbegineing of the file.
It will solve your problem.