如何在Django表单的clean()方法中访问已清理的数据?

时间:2018-02-14 19:35:20

标签: python django forms

我希望在Django表单phone_type中实现一个输入字段,只有在填写了另一个字段phone_number时才需要该字段。我正在阅读关于如何执行此操作的https://www.fusionbox.com/blog/detail/creating-conditionally-required-fields-in-django-forms/577/示例:

def clean(self):
    shipping = self.cleaned_data.get('shipping')

    if shipping:
        msg = forms.ValidationError("This field is required.")
        self.add_error('shipping_destination', msg)
    else:
        # Keep the database consistent. The user may have
        # submitted a shipping_destination even if shipping
        # was not selected
        self.cleaned_data['shipping_destination'] = ''

    return self.cleaned_data

其中模型定义为

from django.db import models

class ShippingInfo(models.Model):
    SHIPPING_DESTINATION_CHOICES = (
        ('residential', "Residential"),
        ('commercial', "Commercial"),
    )

    shipping = models.BooleanField()
    shipping_destination = models.CharField(
        max_length=15,
        choices=SHIPPING_DESTINATION_CHOICES,
        blank=True
    )

但是,在将此代码与https://docs.djangoproject.com/en/2.0/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other处的文档进行比较时,我注意到没有调用super().clean()。我应该

,而不是直接访问self.cleaned_data
cleaned_data = super().clean()
shipping = cleaned_data.get('shipping')

在自定义clean()方法的第一行?

(我也有兴趣了解如何在不需要额外的jQuery / JavaScript代码的情况下使该字段有条件可见,例如使用Django Crispy Forms和/或HiddenInput小部件。)

1 个答案:

答案 0 :(得分:2)

forminstance.is_validforminstance.full_clean将隐式调用您的表单的干净方法,forminstance.cleaned_data将根据表单字段使用正确类型的数据填充dict 。在您发布的示例中调用super以防您在表单类层次结构中具有继承。 为了澄清。如果你有super,它会受到伤害,但如果你没有从没有定义任何字段的表单类继承,它就不会改变任何内容。