我想验证包含可选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有一个必填字段,我每次都无法验证它。
您是否有想法在显示表单的验证中包含地址验证?
谢谢你, 于连
答案 0 :(得分:0)
如果我理解正确,如果至少有1个地址实例,则需要将字段“optional_address”设为必填项
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