Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question