0

我想验证一个包含可选 FK 的表单:

class Address(models.Model):
    mandatory_field = models.CharField(max_length=100)
    optional_field = models.CharField(max_length=20, blank=True, null=True)
class Show(models.Model):
    name = models.CharField(max_length=100)
    optional_address = models.ForeignKey(Address, blank=True, null=True)

class AddressForm(forms.ModelForm):
    class Meta:
        model = Address

class ShowForm(forms.ModelForm):
    class Meta:
        model = Show

在视图表单中,我想像这样执行验证:

if request.method == 'POST':
    form = ShowForm(request.POST)
    if form.is_valid():
        do anything...

但我不知道如何验证 AddressForm。如果至少填写了地址的一个字段,则应进行此验证。由于 AddressForm 有一个必填字段,因此我无法每次都对其进行验证。

您是否有想法将地址验证包含在显示表单的验证中?

谢谢你,朱利安

4

1 回答 1

0

如果我理解正确,如果至少有 1 个地址实例,则需要将“可选地址”字段设为必填

class ShowForm(forms.ModelForm):
    class Meta:
        model = Show

    def __init__(self, *args, **kwargs):
        super(ShowForm, self).__init__(*args, **kwargs)
        if Address.objects.exists():
            self.fields['optional_address'].required = True
于 2013-04-07T05:05:58.723 回答