Question

I have a field "phone" in a form, created with ModelForm. I want to validate this field. Here's the code in models.py:

class UserProfile(models.Model):
     user = models.ForeignKey(User, unique=True)
     phone = models.CharField(max_length=20, validators=[validate_phone])

forms.py:

class UserProfileResetForm(ModelForm):
     class Meta:
         model = UserProfile
         exclude = ('user')

From what I've figured out so far ther are several methods to validate a form created from ModelForm in django. I see at least 3 of them: 1. override phone in UserProfileResetForm as RegexField 2. using validator (as I do now) 3. create clean_phone method in UserProfileResetForm

So I'm a little confused... what is the best way to do this?

Was it helpful?

Solution

Do what you're doing now. if you have a validator that you can place on the model, then not only will it validate all of your modelforms, but it will perform validation in the Admin interface too. If only override clean_phone in the modelform if there's a specific validation you need to perform ONLY IN THAT FORM. The lower the level you can place that validator, the more consistent your application (and data) will be.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top