Mỗi email chỉ RSVP một lần
Thuộc phần Biểu mẫu trong hành trình Django của Coddy. Bài học 18 trên 20.
Chương này là phần của bạn: ba tính năng cho bảng sự kiện, được xây dựng dựa trên những gì bạn đã biết. Mỗi nhiệm vụ nêu rõ trang web cần làm gì; còn code là do bạn viết.
Hiện tại, Ada có thể RSVP cho Đêm nhạc Jazz Thứ Sáu bao nhiêu lần tùy thích, và mỗi lần RSVP đều chiếm một chỗ. Mỗi địa chỉ email chỉ nên giữ một chỗ cho mỗi sự kiện.
Bạn đã có đủ mọi thứ: một phương thức clean_<field>, sự kiện mà biểu mẫu lưu trong self.event, và các lượt RSVP của sự kiện trong self.event.rsvps. Một cách tra cứu nữa sẽ giúp ích: email__iexact so sánh văn bản mà không phân biệt chữ hoa chữ thường, vì Ada@Example.com và ada@example.com đều đến cùng một hộp thư.
Thử thách
Trung bìnhTừ chối lượt RSVP thứ hai bằng cùng một email cho cùng một sự kiện, đồng thời hiển thị This email is already on the guest list. bên cạnh trường email.
- Chữ hoa hay chữ thường không quan trọng:
ADA@Example.comgiốngada@example.com. - Email đó vẫn có thể RSVP cho một sự kiện khác.
RSVP cho Friday Jazz Night bằng ADA@example.com: bạn thấy This email is already on the guest list.
Tự làm thử
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"]
def __init__(self, *args, event=None, **kwargs):
super().__init__(*args, **kwargs)
self.event = event
def clean(self):
cleaned_data = super().clean()
if self.event.rsvps.count() >= self.event.capacity:
raise forms.ValidationError("Sorry, this event is full.")
return cleaned_data
Tất cả bài học trong Biểu mẫu
Tự luyện tập: Playground Django