In my app, I have a custom User model with extra fields like gender, birth_date, etc.
I usually create/update Users using different ways (web services in REST API, Django forms), this means I can't count on Form validation to validate users data.
That's why I was asking myself how to make the User validation as clean as possible.
I decided to do it by overriding save() method in the User class:
def save(self, *args, **kwargs):
# Will prevent from entering bad formated data.
self.full_clean()
# If birth_date provided, need to be younger than current date
if self.birth_date and self.birth_date > datetime.now().date():
raise EXC_FUT_DATE
super(User, self).save(*args, **kwargs)
- I use the full_clean() method first to check that the provided data matches the User fields requirements (eg. gender need to be either 'M' or 'F')
- I make additionnal functional verifications like: "is the birth date in the past?"
It seems to work as expected but I'm not sure to follow best practices here. The whole purpose is to stay DRY (having validation logic at one place) and that this validation logic works for user creation/modification whatever it uses a Django form or a webservice.
Any comment about this pattern? Other idea perhaps? Thanks a lot.