0

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.

David Dahan
  • 10,576
  • 11
  • 64
  • 137

1 Answers1

3

You can use Django forms, because the constructor args are a dictionary. Therefore, build a dict with the values captured from API, instantiate the form with it and call is_valid() method.

data = {'subject': 'hello',
        'message': 'Hi there',
        'sender': 'foo@example.com',
         'cc_myself': True}
f = ContactForm(data)

from docs

jabez
  • 896
  • 1
  • 9
  • 22
  • It would suppose that I have a form that has all my model attributes. That's currently not my case. Should I create a model form? (eg. `class UserForm(ModelForm)` ? Thanks! – David Dahan Dec 08 '14 at 15:21
  • Yes, a ModelForm will do the validation. Also, don't forget to select the fields you want to use, as per [documentation](https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#selecting-the-fields-to-use) – jabez Dec 08 '14 at 16:48
  • 1
    Thanks a lot. I rewrote all validation from the beginning, and it's much much cleaner than processing validation inside `save()`. – David Dahan Dec 08 '14 at 17:20