0
0
Djangoframework~5 mins

Form error handling in Django

Choose your learning style9 modes available
Introduction

Form error handling helps you show users what they did wrong when filling out a form. It makes your app friendly and easy to use.

When you want to check if a user typed a valid email address.
When you need to make sure required fields are not empty.
When you want to tell users if their password is too short.
When you want to highlight mistakes before saving data.
When you want to guide users to fix their input step-by-step.
Syntax
Django
if form.is_valid():
    # process form data
else:
    errors = form.errors
Use form.is_valid() to check if the form data is correct.
Access form.errors to get details about what went wrong.
Examples
Check if form is valid, save data if yes, print errors if no.
Django
if form.is_valid():
    user = form.save()
else:
    print(form.errors)
Get errors as JSON string to send in an API response.
Django
errors = form.errors.as_json()
Loop through each field's errors to show them separately.
Django
for field, error_list in form.errors.items():
    print(f"Error in {field}: {error_list}")
Sample Program

This Django view handles a contact form. It checks if the form data is valid. If not, it redisplays the form with error messages next to the fields.

Django
from django import forms
from django.http import HttpResponse
from django.shortcuts import render

class ContactForm(forms.Form):
    name = forms.CharField(max_length=50)
    email = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea)

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            return HttpResponse('Thank you for your message!')
        else:
            return render(request, 'contact.html', {'form': form})
    else:
        form = ContactForm()
        return render(request, 'contact.html', {'form': form})
OutputSuccess
Important Notes

Always use form.is_valid() before saving or processing data.

Form errors automatically link to the right fields in templates if you use {{ form.as_p }} or similar.

You can customize error messages in your form fields for friendlier feedback.

Summary

Form error handling helps users fix mistakes easily.

Use form.is_valid() to check data and form.errors to get problems.

Show errors in your templates to guide users clearly.