A ModelForm
Part of the Forms section of Coddy's Django journey. Lesson 12 of 20.
Look at EventForm and the Event model side by side: the same fields, written twice. A ModelForm builds its fields from the model. For a Book model:
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ["title", "author", "pages"]The inner Meta class names the model and the fields to use. Each model field becomes the matching form field, and blank=True makes it optional. The list is required, so a field added to the model later never reaches a public form by accident.
clean_<field>() and clean() work the same beside Meta. And the form saves itself: form.save() creates the row from cleaned_data and returns it.
Challenge
EasyTurn EventForm into a ModelForm:
- Its fields come from
Event:title,date,end_date,place,description,capacity. - The field lines go;
clean_date()andclean()stay. new_eventlets the form create the event.
Press Run and add an event.
Try it yourself
import datetime
from django import forms
class EventForm(forms.Form):
title = forms.CharField(max_length=100)
date = forms.DateField()
end_date = forms.DateField(required=False)
place = forms.CharField(max_length=100)
description = forms.CharField(widget=forms.Textarea, required=False)
capacity = forms.IntegerField(min_value=1)
def clean_date(self):
date = self.cleaned_data["date"]
if date < datetime.date.today():
raise forms.ValidationError("The date cannot be in the past.")
return date
def clean(self):
cleaned_data = super().clean()
date = cleaned_data.get("date")
end_date = cleaned_data.get("end_date")
if date and end_date and end_date < date:
raise forms.ValidationError("The event cannot end before it starts.")
return cleaned_data
All lessons in Forms
Practice on your own: Django playground