django forms and it's usage¶
Django forms are used to validate the information submitted by the user and send the error responses back to the user if any and allow valid information inserted into the database.
In django we have two types of forms 1. Django Normal Forms 2. Django Model Forms
Django Normal Forms¶
Django forms used to generate the HTML form fields using the django form fields. we can find more information about the django form fields in the django forms official documentation. In the previous article "django forms getting started" we have seen how to use the django form in the django views. In this article we will learn how to use form fields to create the django forms and write custom validations for form fields.
Most used django form fields¶
- CharField
- It generates a HTML input field of type text
- IntegerField
- It generates a HTML input field of type number
- It comes with integer validator(i.e it validates the users input whether it's integer or not)
- DateField
- It generates a HTML input field of type date
- It comes with date validator on user's input
- URLField
- It generates HTML input field of type text
- It comes with url validator on user's input
- EmailField
- It generates HTML input field of type email
- It validates users input whether it's a valid email or not
- FileField
- It generates HTML input field of type file
- ImageField
- It generates HTML input field of type file
- It validates users input whether it's a valid image or not
- ChoiceField
- It generates HTML select field with options
- It allows user to select a single option.
- MultipleChoiceField
- It generates HTML select field of type multiple select
- It allows user to select multiple options
- BooleanField
- It generates a HTML checkbox field
- CharField(widget=forms.Textarea)
- To generate the HTML textarea we have to pass widget type "forms.Textarea"
Let's create a simple form to store user contacts in the database
Django Normal Form Example¶
Let's create a simple form to store user contacts in the database
forms.py
from django import forms
class UserContactForm(forms.Form)
first_name = forms.CharField()
last_name = forms.CharField()
phone = forms.IntegerField()
def clean_phone(self):
phone = self.cleaned_data.get("phone")
if len(phone) != 10:
raise forms.ValidationError("Invalid phone number")
return phone
def clean(self):
first_name = self.cleaned_data.get("first_name")
last_name = self.cleaned_data.get("first_name")
# Custom Validation Logic
# Here
return self.cleaned_data
In above form we have added a phone number validation method that will check the value of field phone has length of ten or not and raises validation error if the input does not met the validation. We have added field level validation using clean_<field name>
method. We can also make use of "clean" method for dependent fields. We can do awesome things with django forms.
Django Model Forms¶
We have seen how we can use the normal django forms. We can get the same functionality with a few lines of code with model forms just like below for UserContact
model. It's just an example.
models.py
from django.db import models
from django.contrib.auth.models import User
class UserContact(models.Model):
user = models.ForeignKey(on_delete=models.CASCADE, User)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
phone = models.IntegerField()
forms.py
from django import forms
from .models import UserContact
class UserContactForm(forms.ModelForm)
class Meta:
model = UserContact
fields = ('first_name', 'last_name', 'phone')
def clean_phone(self):
phone = self.cleaned_data.get("phone")
if len(phone) != 10:
raise forms.ValidationError("Invalid phone number")
return phone
def clean(self):
first_name = self.cleaned_data.get("first_name")
last_name = self.cleaned_data.get("first_name")
# Custom Validation Logic
# Here
return self.cleaned_data
Like above we can reduce the code and still gets the same functionality and can get extra functionality like save method to save the objects directly into the database.