我正在关注自定义表单集验证的Django Formset Documents上发布的示例,稍作修改。我在示例中发现了一个缺陷,但不确定如何修复它。如果3个输入字段中的1个未完全填写,是否有办法检查数据的唯一性?显然,空表单被记录为“无”,这迫使我至少填写2/3组输入字段(名字/姓氏);否则,它将注册为重复。说明我的意思:
forms.py
class UserInfo (forms.Form):
first_name = forms.CharField (max_length = 20, required = False)
last_name = forms.CharField (max_length = 20, required = False)
class BaseUserInfoFormSet (BaseFormSet):
def clean (self):
if any (self.errors):
return
firstnames = []
lastnames = []
errors = []
for form in self.forms:
firstname = form.cleaned_data.get ('first_name')
lastname = form.cleaned_data.get ('last_name')
if ((firstname in firstnames) or (lastname in lastnames)) and len (errors) < 2:
errors.append ('First and/or last name must be unique')
if ((firstname == '') or (lastname == '')) and len (errors) < 2:
errors.append ('First and/or last name cannot be blanked')
firstnames.append (firstname)
lastnames.append (lastname)
print ('First Name List: ', firstnames)
print ('Last Name List: ', lastnames)
if errors:
raise forms.ValidationError (errors)
return self.cleaned_data
只填写了一组firstname / lastname,这是控制台的结果。
First Name List: ['John']
Last Name List: ['Doe']
First Name List: ['John', None]
Last Name List: ['Doe', None]
First Name List: ['John', None, None]
Last Name List: ['Doe', None, None]
由于存在重复的“无”,因此触发了错误:
errors.append ('First and/or last name must be unique')
答案 0 :(得分:0)
只是为了澄清,您不需要空值,为什么不填写所需的字段。这将完全删除None问题,因为那时将需要所有字段。
否则,如果值不为空,则只能将值添加到列表中
if firstname:
firstnames.append(firstname)
if lastname:
lastnames.append(lastname)
答案 1 :(得分:0)
我想我通过添加&#39; if&#39;来修复它。检查无的声明。
if (firstname or lastname) is not None:
firstnames.append (firstname)
lastnames.append (lastname)