אירוע מלא
חלק מהיחידה טפסים במסלול ה-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.
אתגר
בינוניאירועים מלאים מסרבים לבקשות RSVP.
- בקובץ
events/forms.py, הוסף ל־RSVPFormמתודת__init__ששומרת את הארגומנט בשם המפתחeventב־self.eventומעבירה את שאר הארגומנטים אלsuper().__init__. - במתודת
clean()שלה, כאשר האורחים ממלאים אתcapacity, העלה את השגיאהSorry, this event is full.גם כשנותר מקום אחד, אורח עדיין יכול להירשם. - ב־
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"]
השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.
כל השיעורים ביחידה טפסים
תרגלו בעצמכם: Django אונליין