我正在尝试清理我的内联formset数据。我有三个规则:1)必须提供至少一个名称,2)如果指定名称,则必须指定第一个和最后一个,以及3)没有空格。保存数据后,空间仍保存到数据库中。我做错了什么?
另一个问题是未显示验证错误。那是为什么?
forms.py:
class UserNameForm(forms.models.BaseInlineFormSet):
def clean(self):
super(UserNameForm, self).clean()
count = 0
for form in self.forms:
try:
firstName = form.cleaned_data.get("name_first")
middleName = form.cleaned_data.get("name_middle")
lastName = form.cleaned_data.get("name_last")
if firstName or middleName or lastName:
if len(firstName) == 0 or len(lastName) == 0:
raise forms.ValidationError("First and Last name are required.")
if form.cleaned_data and not form.cleaned_data.get('DELETE', False):
count += 1
form.cleaned_data['name_first'] = firstName.replace(" ",'')
form.cleaned_data["name_middle"] = middleName.replace(" ",'')
form.cleaned_data["name_last"] = lastName.replace(" ",'')
except AttributeError:
pass
if count < 1:
raise forms.ValidationError('You must have at least one order')
views.py
UserNameFormSet = inlineformset_factory(Profile, Alias, formset=UserNameForm, extra=2, can_delete=True )
if request.method == 'POST':
cNameFormSet = UserNameFormSet(request.POST, request.FILES, instance=cProfile)
if cNameFormSet.is_valid():
testResults = cNameFormSet.save(commit=False)
for form in testResults:
form.save()
答案 0 :(得分:0)
您可以同时应用表单和表单集。使用formset验证表单和表单中的数据,以验证表单中的数据并引发验证错误。
UserNameFormSet = inlineformset_factory(Profile,
Alias,
form=UserNameForm,
formset=AtLeastOne,
extra=2,
can_delete=True )
class AtLeastOne(forms.models.BaseInlineFormSet):
def clean(self):
count = 0
for form in self.forms:
try:
if form.cleaned_data and not form.cleaned_data.get('DELETE', False):
count += 1
except AttributeError:
pass
if count < 1:
raise forms.ValidationError('You must have at least one name')
class UserNameForm(forms.ModelForm):
class Meta:
model = Alias
def clean(self):
cleaned_data = self.cleaned_data
# Check 1: Must have first and last.
firstName = cleaned_data.get("name_first")
middleName = cleaned_data.get("name_middle")
lastName = cleaned_data.get("name_last")
if firstName or middleName or lastName:
if len(firstName) == 0 or len(lastName) == 0:
raise forms.ValidationError("First and Last name are required.")
# Check 2: No spaces.
cleaned_data["name_first"] = firstName.replace(" ",'')
cleaned_data["name_middle"] = middleName.replace(" ",'')
cleaned_data["name_last"] = lastName.replace(" ",'')
return cleaned_data