A Full Event
Part of the Forms section of Coddy's Django journey. Lesson 17 of 20.
The Pottery Class has 2 places and 2 guests, yet its form still takes more. The rule belongs in the form, but only the view knows which event the form is for.
A form is a Python class, so you can give it your own __init__. Take the extra value as a keyword argument, keep it on self, and pass the rest to super().__init__(). A bid form that needs the auction item:
class BidForm(forms.Form):
amount = forms.IntegerField()
def __init__(self, *args, item=None, **kwargs):
super().__init__(*args, **kwargs)
self.item = item
def clean_amount(self):
amount = self.cleaned_data["amount"]
if amount <= self.item.top_bid:
raise forms.ValidationError("Bid more than the top bid.")
return amountThe view passes the item each time it builds the form: BidForm(request.POST, item=item). Naming item in the signature keeps it out of **kwargs; Django's form does not know it and would raise TypeError.
Challenge
MediumFull events refuse RSVPs.
- In
events/forms.py, giveRSVPForman__init__that keeps a keyword argumenteventonself.eventand passes the rest tosuper().__init__. - In its
clean(), when guests fill thecapacity, raiseSorry, this event is full.One place left still takes a guest. - In
event_detail, passeventto bothRSVPFormcalls.
RSVP to the Pottery Class: you see Sorry, this event is full.
Try it yourself
import datetime
from django import forms
from .models import RSVP, Event
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = ["title", "date", "end_date", "place", "description", "capacity"]
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
class RSVPForm(forms.ModelForm):
class Meta:
model = RSVP
fields = ["name", "email"]
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Forms
Practice on your own: Django playground