gpt4 book ai didi

python - Django:form_valid 和模型验证

转载 作者:行者123 更新时间:2023-12-02 14:50:10 28 4
gpt4 key购买 nike

我正在 Django 中创建一个汽车预订应用程序。用户可以为给定的汽车创建预订。这发生在 /reservation/<car_id>/add .此表单不包含 Car 字段,因为 id 在 URL 中给出。现在我想向 Reservation 模型添加验证,这样预订就不会重叠。我有以下代码(最小版本):

# models.py

class Car(models.Model):
name = models.CharField(max_length=200)


class Reservation(models.Model):
car = models.ForeignKey(Car, on_delete=models.CASCADE)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField()

def clean(self):
# Check if overlaps with other reservations in self.car.reservation_set

# views.py

class ReservationAdd(LoginRequiredMixin, CreateView):
template_name = 'reservation/reservation_add.html'
model = Reservation
form_class = ReservationAddForm

def form_valid(self, form):
form.instance.car = Car.objects.get(pk=self.kwargs['car_id'])
form.instance.owner = self.request.user
return super().form_valid(form)

# forms.py

class ReservationAddForm(forms.ModelForm):

class Meta:
fields = ('start_time', 'end_time')
model = Reservation

现在我在 Reservation.clean 收到以下错误方法:

reservation.models.Reservation.car.RelatedObjectDoesNotExist: Reservation has no car.

在我看来 clean方法在 form_valid 之前被调用方法。所以我认为我的设计并不完全正确。执行此操作的正确方法是什么?

最佳答案

是的。 form_valid 表示“表单被确认为有效后运行的代码”。

您需要进行一些更改。首先,将验证移至 ReservationAddForm 本身;其次,将 Car 实例传递到该表单中。所以:

class ReservationAddForm(forms.ModelForm):

class Meta:
fields = ('start_time', 'end_time')
model = Reservation

def __init__(self, *args, **kwargs):
self.car = kwargs.pop('car')
super().__init__(*args, **kwargs)

def clean(self):
... do something with self.car

class ReservationAdd(LoginRequiredMixin, CreateView):
template_name = 'reservation/reservation_add.html'
model = Reservation
form_class = ReservationAddForm

def get_form_kwargs(self):
self.car = Car.objects.get(pk=self.kwargs['car_id'])
kwargs = super().get_form_kwargs()
kwargs['car'] = self.car
return kwargs

def form_valid(self, form):
form.instance.car = self.car
form.instance.owner = self.request.user
return super().form_valid(form)

关于python - Django:form_valid 和模型验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56186730/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com