1

I am fairly new to django and I am trying to constrain a django model field such that the age less than 25 years is shown as an error (using the datefield). So, I have the following model:

dob = models.DateField(blank=False, )

I am wondering how one can apply the above constraint in a django model. Thanks.

JohnJ
  • 6,736
  • 13
  • 49
  • 82

2 Answers2

2

I've just come across the same problem, and here is my solution for a custom field validator that checks for a minimum age value:

from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _
from django.core.validators import BaseValidator
from datetime import date

def calculate_age(born):
    today = date.today()
    return today.year - born.year - \
           ((today.month, today.day) < (born.month, born.day))

@deconstructible
class MinAgeValidator(BaseValidator):
    message = _("Age must be at least %(limit_value)d.")
    code = 'min_age'

    def compare(self, a, b):
        return calculate_age(a) < b

The calculate_age snippet is from this post.

Usage:

class MyModel(models.Model):
    date_of_birth = models.DateField(validators=[MinAgeValidator(18)])
null
  • 169
  • 1
  • 13
Dubrzr
  • 317
  • 3
  • 16
  • Your validation class is incomplete. Python Doc says:You can also use a class with a **__call__() method** for more complex or configurable validators. RegexValidator, for example, uses this technique. If a class-based validator is used in the validators model field option, you should make sure it is serializable by the migration framework by adding deconstruct() and __eq__() methods. – Pek Jan 25 '20 at 06:27
1

You need to create custom field validator.

Unfortunately you will need to hardcode the age value inside validator function, since it doesn't allow you to pass any arguments.

Then to calculate age use this snippet to correctly cover leap years.

Community
  • 1
  • 1
mariodev
  • 13,928
  • 3
  • 49
  • 61