首页 文章

BaseModelFormset中自定义clean()方法的KeyError

提问于
浏览
0

我已阅读有关100x的Forms和Formset Django文档 . 为了清楚地说明这一点,这可能是我第一次使用super()或尝试从另一个类重载/继承(对我来说很重要) .

发生了什么?我正在视图中制作一个django-model-formset,我将它传递给模板 . formset继承的模型恰好是ManyToMany关系 . 我希望这些关系是唯一的,所以如果我的用户正在创建一个表单并且他们不小心为ManyToMany选择了相同的Object,我希望它失败验证 .

我相信我已经正确编写了这个自定义“BaseModelFormSet”(通过文档),但我得到了一个KeyError . 它告诉我,它找不到cleaning_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..

2 回答

  • 0

    是不是干净的方法错过了一个return语句?如果我没记错的话应该总是返回cleaning_data . 此超级调用还返回cleaning_data,因此您应该在那里分配它 .

    def clean(self):
        cleaned_data = super(BaseTechOnsiteFormset, self).clean()
        # use cleaned_data from here to validate your form
        return cleaned_data
    

    有关详细信息,请参阅:the django docs

  • 1

    我使用Django shell手动调用表单 . 我发现我正在从视图返回的所有表单上执行clean()方法 . 有2个数据填写,2个空白 . 当我的clean()方法遍历它们时,它返回了KeyError,当它到达第一个空白时 .

    我通过使用try-statement并传递KeyErrors来修复我的问题 .

相关问题