我已经阅读了大约 100 倍的 Forms 和 Formset Django 文档。为了清楚起见,这可能是我第一次使用 super() 或尝试从另一个类重载/继承(对我来说很重要。)
发生了什么?我正在视图中制作 django-model-formset 并将其传递给模板。表单集继承的模型恰好是多对多关系。我希望这些关系是唯一的,因此如果我的用户正在创建一个表单并且他们不小心为 ManyToMany 选择了相同的对象,我希望它验证失败。
我相信我已经正确地编写了这个自定义的“BaseModelFormSet”(通过文档),但我得到了一个 KeyError。它告诉我它找不到cleaned_data['tech'] 并且我在下面评论的行中的'tech' 一词上得到了KeyError。
该模型:
class Tech_Onsite(models.Model):
tech = models.ForeignKey(User)
ticket = models.ForeignKey(Ticket)
in_time = models.DateTimeField(blank=False)
out_time = models.DateTimeField(blank=False)
def total_time(self):
return self.out_time - self.in_time
自定义的 BaseModelFormSet:
from django.forms.models import BaseModelFormSet
from django.core.exceptions import ValidationError
class BaseTechOnsiteFormset(BaseModelFormSet):
def clean(self):
""" Checks to make sure there are unique techs present """
super(BaseTechOnsiteFormset, self).clean()
if any(self.errors):
# Don't bother validating enless the rest of the form is valid
return
techs_present = []
for form in self.forms:
tech = form.cleaned_data['tech'] ## KeyError: 'tech' <-
if tech in techs_present:
raise ValidationError("You cannot input multiple times for the same technician. Please make sure you did not select the same technician twice.")
techs_present.append(tech)
观点:(总结)
## I am instantiating my view with POST data:
tech_onsite_form = tech_onsite_formset(request.POST, request.FILES)
## I am receiving an error when the script reaches:
if tech_onsite_form.is_valid():
## blah blah blah..