Django unique model fields validation in form
validate_unique is a Model
method.
Running the superclass clean
method should take care of model uniqueness checks given a ModelForm
.
class MyModelForm(forms.ModelForm):
def clean(self):
cleaned_data = super(MyModelForm, self).clean()
# additional cleaning here
return cleaned_data
There is a warning on the django docs specifically about overriding clean on ModelForm
s, which automatically does several model validation steps.
simple way to achieve uniqueness to a field, just use "unique=True" in the model field. Example:
email = models.EmailField(verbose_name=_('Email'), max_length=255, unique=True)
phone = models.CharField(verbose_name=_('Phone Number'), max_length=14, unique=True)
But if you really want to achieve this through form, or situation demands it, for example, in the above code section, here phone number is a character field. uniqueness is difficult to achieve here because for the system 0171-xxxxxxx and 0171xxxxxxx are different numbers but actually they are same. It can be easily validated through form's clean_phone method. Here the digit is parsed from the string(character field) before checking uniqueness.
def clean_phone(self):
phone = self.cleaned_data.get("phone")
# parse digits from the string
digit_list = re.findall("\d+", phone)
phone = ''.join(digit_list)
if CustomUser.objects.filter(phone=phone).exists():
raise forms.ValidationError("phone number is already exists")
return phone
I solve it by adding validate_unique()
to save()
class Server( models.Model ):
host = models.GenericIPAddressField( blank = False, null = False, unique = True )
name = models.CharField( blank = False, null = False, unique = True, max_length = 55 )
def save(self, *args,**kwargs):
self.validate_unique()
super(Server,self).save(*args, **kwargs)
It works for me. I don't know about you.