因此,在我的表单中,当我选择一个时间选择时,例如“晚上 8 点”,它会作为不同的时间存储在数据库中,我检查了表单提交,它正在作为正确的时间提交,但没有保存那么,代码有什么问题吗?
from django.core.exceptions import ValidationError
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
from django.core.validators import MinValueValidator, MaxValueValidator
class Booking(models.Model):
name = models.ForeignKey(User, on_delete=models.CASCADE)
special_occasion = models.CharField(max_length=11, choices=[('None', 'None'), ('anniversary', 'Anniversary'), ('date', 'Date'), ('business', 'Business')])
meal_day = models.DateField()
number_of_guests = models.PositiveIntegerField(
null=True,
validators=[MinValueValidator(1), MaxValueValidator(6)]
)
customer_name = models.CharField(max_length=50)
TIME_CHOICES = [
('13:00', '01:00 PM'),
('14:00', '02:00 PM'),
('15:00', '03:00 PM'),
('16:00', '04:00 PM'),
('17:00', '05:00 PM'),
('18:00', '06:00 PM'),
('19:00', '07:00 PM'),
('20:00', '08:00 PM'),
]
meal_time = models.CharField(max_length=5, choices=TIME_CHOICES)
def clean(self):
if self.meal_day and self.meal_day < now().date():
raise ValidationError("Cannot make a booking in the past.")
existing_bookings = Booking.objects.filter(meal_time=self.meal_time, meal_day=self.meal_day)
if self.pk:
existing_bookings = existing_bookings.exclude(pk=self.pk)
if existing_bookings.exists():
raise ValidationError("A booking already exists at this time on this day.")
super().clean() # Call parent's clean method for remaining validations
def save(self, *args, **kwargs):
if not self.pk:
available_times = [choice[0] for choice in self.TIME_CHOICES]
booked_times = Booking.objects.filter(meal_day=self.meal_day).values_list('meal_time', flat=True)
available_times = [time for time in available_times if time not in booked_times]
if available_times:
self.meal_time = available_times[0]
else:
raise ValidationError("No available time slots for the selected day.")
super().save(*args, **kwargs)
这条线
if available_times:
self.meal_time = available_times[0]
始终将用餐时间设置为新的、未保存的预订的第一个可用时间,而不是选择的时间。我认为你根本不需要那个 IF 语句,你只需要引发错误
if not available_times