Menu
CoddyTech

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 class, so it can take more arguments. Take yours as a keyword in __init__, keep it on self, and hand the rest to Django's __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 amount

The 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 icon

Challenge

Medium

Refuse RSVPs to a full event with Sorry, this event is full.:

  • Give RSVPForm the event as a keyword argument event, and use it in a check of the whole form.
  • An event with one place left still takes one more guest.
  • Pass the event wherever event_detail builds the form.

Press Run and RSVP to the Pottery Class.

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"]
quiz iconTest yourself

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