K
K
Konstantin Malyarov2018-03-30 17:33:47
Django
Konstantin Malyarov, 2018-03-30 17:33:47

How to do age validation?

How to validate the age field so that the date of birth is no more than the current one (it cannot be tomorrow or a month ahead), and the age in total is not older than 120 years?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-03-30
@Konstantin18ko

Based on the documentation :

from datetime import timedelta
from django.db import models
from django.core.exceptions import ValidationError
from django.utils import timezone


class Person(models.Model):
    dob = models.DateField('Дата рождения')

    def clean_fields(self, exclude=None):
        super().clean_fields(exclude=exclude)

        now = timezone.now()
        if self.dob > (now - timedelta(days=30)):
            raise ValidationError('Рано ещё заносить в базу')
        if (now.year - self.dob.year) > 120:
            raise ValidationError('Поздно уже заносить в базу')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question