Introduction to Django Forms
Django forms live on the backend of a Django application however you can use them for things like generating HTML forms to render on the front end or validating incoming data. A form is just a class that contains certain fields and every field has a widget associated with it which is used to tell Python which HTML tag it should use for this particular field when generating the HTML for us so that we can display it on the client-side.
Django forms make our lives easier by taking care of common tasks so we would spend less time coding a form from scratch.
To better understand this concept let’s take a look at an example. If you have not been following this series of articles on Django, we have built a simple project named sample_project within which we have a simple app named sample_app. At this point we have the following structure for our project:
Creating a Django Form:
Similar to creating Models in Django, we need to specify the fields and their respective types while creating a Django form. For instance, imagine creating a user registration form that takes input such as name(CharField), email(EmailField), contact(IntegerField), date of birth(DateField) etc. While creating a Django form, we need to specify the fields and their type. The general syntax for creating a form is given below:
So now let’s suppose we are creating a form to display to the user that asks for a Name, Age, Qualification, and an email. To do this let’s first create a forms.py file inside our sample_app. After creating the file add in the below code:
# creating a form class InputForm(forms.Form): name = forms.CharField(max_length = 200) qualification = forms.ChoiceField(choices = [("garduate","Graduate"), ("post_graduate","Post graduate")]) age = forms.IntegerField() email = forms.EmailField()
In the above code, we have created a form (ie InputForm), that has a name field that can hold a maximum of 200 characters, a qualification field that gives the user a choice between 2 options, an age field that holds numbers, and an email field that only stores email address.
Explore Popular Online Courses
Now to render this form into a view, we need to move to sample_app/views.py file and create a sample_view function as below:
# import render from django shortcuts module from django.shortcuts import render from .forms import InputForm # Create your sample_view def sample_view(request): context ={} context['form']= InputForm() return render(request, "sample_view.html", context)
The above just receives the content from the form field. It renders them as the context in the HTML file. So we need to have an HTML page (ie sample_view.html) where we are to render our form. To do so, first, create a directory called Templates and then, add a file called sample_view.html to it. Then add in the below code in the HTML file:
|
Now when we run the server and visit the http://127.0.0.1:8000/ link we can see our form as shown below:
Concept of ModelForm:
Now that we know how to implement a simple form in Django, let’s talk about the data that is submitted through the form. The whole purpose of a form is to get data directly from the users for backend computation. This data need to be mapped with corresponding models for storage (as most data-driven applications do).
To simplify this mapping, we can make use of the Django ModelForm class. The Django ModelForm class allows us to convert a Django model into a form. This makes the developer’s life simpler and helps them avoid all the effort needed to do the mapping after creating a form.
Check out Django courses online
Let’s take a look at how it’s done. Open up the sample_app/model.py file, and add in the below code:
# import the standard Django Model # from built-in library from django.db import models
# Creating a new model class # named "MyModel" class MyModel(models.Model): # fields in the model name = models.CharField(max_length = 200) age = models.IntegerField(default=18) email = models.EmailField(null=True) # here we have renamed the model instances # with their name def __str__(self): return self.name
It is a simple Django model (MyModel), which has three fields ie name, age, and email. As we made changes to our model file, run the below commands in conjuncture to establish the changes to the database:
python manage.py makemigrations python manage.py migrate
Now, we aim to get this data model mapped to a form. So to create a form respective to MyModel, open up the sample_app/forms.py file and add in the following code:
# import form class from django from django import forms # import MyModel from models.py file from .models import GeeksModel # create a ModelForm class InputForm(forms.ModelForm): # here we need to specify # the model name that is to used class Meta: model = MyModel fields = "__all__"
Now if we run the server using the below command and check our project, it would look like below:
We also need to store the data from the form to the database. For that, we need to update our view. So open up the sample_app/views.py file and add in the below code:
# import render from django shortcuts module from django import forms from django.shortcuts import render from .forms import InputForm # Create your sample_view def sample_view(request): form = InputForm() # handling the submit request if request.method == "POST": form = InputForm(request.POST) #save the form data form.save() context ={'form':form} return render(request, "sample_view.html", context)
Now let’s add some data to the form we created and submit the form. We will input the following data into our database:
Now, to verify that this data is received and stored by our model in the database, we can open up our admin panel and check the same as shown below:
Conclusion
In this article we covered the following concepts:
- What is Django Form?
- Creating a Django Form
- Creating forms from Models
- Storing form data to the database
Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.
Click here to submit its review with Shiksha Online.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio