Django Forms
Django Forms
Django Forms provide a convenient way to work with HTML forms in Django applications.
They handle form rendering, validation, and data manipulation.
Let's explore how to create forms using Django Forms and ModelForms, handle form submissions, and customize form behavior and appearance:
Creating forms using Django Forms and ModelForms:
The great thing about Django Forms is that they are modeled by classes written in Python.
Note that django.forms.Form can be your friend in building forms from scratch or simply using django.forms.ModelForm to automatically generate forms based on Django models.
# forms.py
from django import forms
from .models import MyModel
class MyForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['name', 'email']
Here is the case, where MyForm is a standard form but MyModelForm is generated from the model MyModel.
Form validation and handling form submissions:
Django Forms handle form validation automatically based on field definitions and form logic.
You can access form data using the cleaned_data attribute after form validation.
# views.py
from django.shortcuts import render
from .forms import MyForm
def my_form_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
# Process form data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
# Additional processing
else:
form = MyForm()
return render(request, 'my_template.html', {'form': form})
Customizing form behavior and appearance:
You can create the sort of form behavior you want and adjust how the form looks by using the different features and attributes that Django Forms give you.
# forms.py
class MyForm(forms.Form):
name = forms.CharField(
max_length=100,
widget=forms.TextInput(attrs={'class': 'form-control'})
)
email = forms.EmailField(
widget=forms.EmailInput(attrs={'class': 'form-control'})
)
Here, I introduced style appearance to the form widgets by using CSS classes in the form.