当所有字段都为空但当我填写任何一个字段并提交该表单集时,内联表单集有效吗?
forms.py
class ContactPersonForm(forms.ModelForm):
phone_number = PhoneNumberField(error_messages={'required': 'Please enter your phone number'}, widget=forms.TextInput(attrs={'placeholder': _('Mobile Number')}))
mobile_number = PhoneNumberField(error_messages={'required': 'Please enter your phone number'}, widget=forms.TextInput(attrs={'placeholder': _('Mobile Number')}))
class Meta:
model = ContactPerson
exclude = ('client',)
widgets = {
'first_name': forms.TextInput(attrs={'placeholder': _('First Name')}),
'last_name': forms.TextInput(attrs={'placeholder': _('Last Name')}),
'email': forms.EmailInput(attrs={'placeholder': _('Email')}),
'phone_number': forms.TextInput(attrs={'placeholder': _('Phone Number')}),
'mobile_number': forms.TextInput(attrs={'placeholder': _('Mobile Number')}),
'skype_name': forms.TextInput(attrs={'placeholder': _('Skype Name / Number')}),
'designation': forms.TextInput(attrs={'placeholder': _('Designation')}),
'department': forms.TextInput(attrs={'placeholder': _('Department')}),
}
ContactPersonFormSet = inlineformset_factory(Client, ContactPerson, form=ContactPersonForm, extra=1)
models.py
class ContactPerson(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
salutation = models.CharField(max_length=4, choices=SALUTATIONS)
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
email = models.EmailField()
phone_number = models.CharField(max_length=20)
mobile_number = models.CharField(max_length=20)
skype_name = models.CharField(_('Skype Name / Number'), max_length=128)
designation = models.CharField(max_length=128)
department = models.CharField(max_length=128, null=True)
答案 0 :(得分:0)
您可以通过继承BaseInlineFormSet
并使用属性has_changed()
class ContactPersonFormSet(forms.BaseInlineFormSet):
def clean(self):
if self.has_changed() == False:
raise forms.ValidationError('Please add at least one contact person.')
,然后在您的fomset_facotry中指定它,例如
ContactPersonFormSet = inlineformset_factory(Client, ContactPerson, form=ContactPersonForm, formset=ContactPersonFormSet, extra=1)