Django Forms
When one creates a Form class, the most important part is defining the fields of the form. Each field has custom validation logic, along with a few other hooks. Forms are basically used for taking input from the user in some manner and using that information for logical operations on databases. For example, Registering a user by taking input as his name, email, password, etc. Django maps the fields defined in Django forms into HTML input fields. Django handles three distinct parts of the work involved in forms:
- preparing and restructuring data to make it ready for rendering
- creating HTML forms for the data
- receiving and processing submitted forms and data from the client
Note: All types of work done by Django forms can be done with advanced HTML stuff, but Django makes it easier and efficient especially the validation part. Once you get hold of Django forms you will just forget about HTML forms.
Creating Django Forms
Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in the form and of what type. For example, to input, a registration form one might need First Name (CharField), Roll Number (IntegerField), and so on.
To create a Django form, first create a forms.py inside the app folder.
Python3
from django import forms class GeeksForm(forms.Form): title = forms.CharField(max_length = 200 ) description = forms.CharField(widget = forms.Textarea) image = forms.ImageField() |
Let’s create a different view function for handling forms and we will map this view function to a different URL. In the above created views.py file import the GeeksForm from the forms.py and create the below function.
views.py
Python3
from .forms import GeeksForm def geeks_form(request): context = {} context[ 'form' ] = GeeksForm return render(request, "form.html" , context = context) |
Map this function to a different URL let’s say we will map this function to the http://127.0.0.1:8000/add/. To do this go to urls.py file of the app and another path for above URL.
urls.py
Python3
from django.urls import path from . import views urlpatterns = [ path(' ', views.geeks_view, name=' geeks_view'), path( 'add/' , views.geeks_form, name = "geeks_form" ) ] |
Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). A form comes with 3 in-built methods that can be used to render Django form fields.
- {{ form.as_table }} will render them as table cells wrapped in <tr> tags
- {{ form.as_p }} will render them wrapped in <p> tags
- {{ form.as_ul }} will render them wrapped in <li> tags
Now let’s make the form.html for rendering our form.
HTML
< form action = "" method = "POST" > {% csrf_token %} {{form.as_p}} < input type = "submit" value = "submit" > </ form > |
After doing this save all the files and go to http://127.0.0.1:8000/add/ to see the form we created. It should look like this –
We can also see that our form is validated automatically. We cannot submit an empty form.
Create Django Form from Models
Django ModelForm is a class that is used to directly convert a model into a Django form. To create a form directly for our model, dive into forms.py and Enter the following –
Python3
from django import forms from .models import GeeksModel class GeeksForm(forms.ModelForm): class Meta: model = GeeksModel fields = [ 'title' , 'description' , 'image' ] |
Now visit http://127.0.0.1:8000/add/ you will see the same form as above but with less code.
Both the Django forms we created are similar but the only difference is the save() method. Every ModelForm has a save() method which saves the database object from the data bound to the form. In simpler words we will be able to save the data to our database using the ModelForm only. For this change the view method as follow –
views.py
Python3
def geeks_form(request): if request.method = = 'POST' : form = GeeksForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect( "geeks_view" ) else : # uncomment the below line to see errors # in the form (if any) # print(form.errors) return redirect( "geeks_form" ) else : context = {} context[ 'form' ] = GeeksForm return render(request, "form.html" , context = context) |
Note: Add enctype= multipart/form-data to our <form> element in our template tag. If we don’t have this then our request.FILES will always be empty and our form will not validate.
Let’s add some data with our form and see if its get saved in our database or not.
After hitting submit the form gets saved automatically to database. We can verify it from the above GIF.
Refer to the below articles to get more information about Django Forms –
Python Web Development With Django
Python Django is a web framework that allows to quickly create efficient web pages. Django is also called batteries included framework because it provides built-in features such as Django Admin Interface, default database – SQLite3, etc. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use.