python - How to Check for Unique Data in Django Form? -
i'm following examples posted on django formset documents regarding custom formset validation slight modification. found flaw in example unsure how fix it. there way check uniqueness in data if 1 of 3 input field not filled out? apparently, empty form recorded "none" forces me @ least fill out 2/3 sets of input field (firstname/lastname); otherwise, register duplicates. illustrate mean:
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 (self.errors): return firstnames = [] lastnames = [] errors = [] 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)) , len (errors) < 2: errors.append ('first and/or last name must unique') if ((firstname == '') or (lastname == '')) , len (errors) < 2: errors.append ('first and/or last name cannot 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
with 1 set of firstname/lastname filled out, here's result console.
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]
because there duplicate "none", triggered error:
errors.append ('first and/or last name must unique')
just clarify, not need blank values, why not make fields required. remove none issue altogether, fields required.
else, add values list if not empty
if firstname: firstnames.append(firstname) if lastname: lastnames.append(lastname)
Comments
Post a Comment