NelsonLabs
Django/Forms & Validation

Forms & Validation

Django forms handle validation, error display, and HTML rendering. They're tightly integrated with models โ€” ModelForm generates a form from a model with one class.

Creating and using forms
python
# courses/forms.py
from django import forms
from .models import Course

class ContactForm(forms.Form):
    name    = forms.CharField(max_length=100)
    email   = forms.EmailField()
    message = forms.CharField(widget=forms.Textarea(attrs={"rows": 5}))
    course  = forms.ChoiceField(choices=[("html", "HTML"), ("css", "CSS"), ("js", "JS")])

# ModelForm โ€” generates fields from a model automatically
class CourseForm(forms.ModelForm):
    class Meta:
        model  = Course
        fields = ["title", "slug", "description", "level", "is_live"]
        widgets = {
            "description": forms.Textarea(attrs={"rows": 4}),
        }
Handling form submission in a view
python
def contact(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            # form.cleaned_data โ€” validated and cleaned values
            name    = form.cleaned_data["name"]
            email   = form.cleaned_data["email"]
            message = form.cleaned_data["message"]

            send_email(name, email, message)  # your logic here
            return redirect("contact-success")
    else:
        form = ContactForm()  # empty form for GET request

    return render(request, "contact.html", {"form": form})