Every web app collects input: sign-up details, enquiries, orders. Accepting that input safely is one of the most important jobs of the back end. Django forms do most of the hard work for you.
Form vs ModelForm
- Form is for input that is not tied directly to a database table, such as a search box or a contact form you only email.
- ModelForm builds the form from a model, so fields, types and basic validation come from your model definition, and
form.save()writes a row to the database.
class EnquiryForm(forms.ModelForm):
class Meta:
model = Enquiry
fields = ["name", "phone", "course"]
The view pattern
A typical view creates the form with request.POST when the form is submitted, calls form.is_valid(), saves and redirects when it passes, and re-displays the form with errors when it fails. Redirecting after a successful save prevents duplicate submissions when the user refreshes the page.
Built-in and custom validation
Django already checks required fields, maximum lengths, email formats and number ranges. For your own rules, add a clean_<field>() method:
def clean_phone(self):
phone = self.cleaned_data["phone"].strip()
if not phone.isdigit() or len(phone) != 10:
raise forms.ValidationError("Enter a 10-digit phone number.")
return phone
For rules that involve two fields, such as “end date must be after start date”, override clean() instead.
Security you get for free
- CSRF protection: include
{% csrf_token %}in every POST form. - Escaping: Django templates escape output, which protects against script injection.
- Cleaned data: always read from
form.cleaned_data, never directly fromrequest.POST.
Never trust the browser alone
HTML attributes like required improve the user experience, but anyone can bypass them. Server-side validation in the form is what actually protects your data.
Next, read Django models and migrations and build an enquiry form with phone validation as a portfolio exercise.
These topics are practised with projects in our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
