Menu
CoddyTech

אירוע מלא

חלק מהיחידה טפסים במסלול ה-Django של Coddy. שיעור 17 מתוך 20.

בכיתת הקדרות יש 2 מקומות ו־2 אורחים, ובכל זאת הטופס שלה עדיין מאפשר יותר. הכלל שייך לטופס, אבל רק התצוגה יודעת לאיזה אירוע מיועד הטופס.

טופס הוא מחלקת Python, ולכן אפשר להגדיר לו __init__ משלך. קבל את הערך הנוסף כארגומנט מילת מפתח, שמור אותו ב־self, והעבר את השאר אל super().__init__(). טופס הצעה שזקוק לפריט המכירה הפומבית:

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

התצוגה מעבירה את הפריט בכל פעם שהיא בונה את הטופס: BidForm(request.POST, item=item). ציון item בחתימה משאיר אותו מחוץ ל־**kwargs; הטופס של Django לא מכיר אותו, ולכן תיזרק שגיאת TypeError.

challenge icon

אתגר

בינוני

אירועים מלאים מסרבים לבקשות RSVP.

  1. בקובץ events/forms.py, הוסף ל־RSVPForm מתודת __init__ ששומרת את הארגומנט בשם המפתח event ב־self.event ומעבירה את שאר הארגומנטים אל super().__init__.
  2. במתודת clean() שלה, כאשר האורחים ממלאים את capacity, העלה את השגיאה Sorry, this event is full. גם כשנותר מקום אחד, אורח עדיין יכול להירשם.
  3. ב־event_detail, העבר את event לשתי הקריאות ל־RSVPForm.

נרשמת לאירוע Pottery Class: מוצגת ההודעה Sorry, this event is full.

נסו בעצמכם

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 iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה טפסים

תרגלו בעצמכם: Django אונליין