Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date Validation --> end date must be greater than start date

I need to write a script where it validates the end date is greater than the start date.

Also the start date/end date can not be before the current date. This needs to be written in Django 1.8.

like image 686
CondeMonkey9559 Avatar asked Jan 27 '23 03:01

CondeMonkey9559


1 Answers

You can override the Model.clean(..) method [Django-doc] for this. If you use a ModelForm [Django-doc], then it will automatically call .clean() on the model instance to check if the constraint is satisfied.

from django.db import models
from django.utils import timezone

class MyModel(models.Model):
    start = models.DateTimeField()
    end = models.DateTimeField()

    def clean(self):
        super().clean()
        if not (timezone.now() <= self.start <= self.end):
            raise ValidationError('Invalid start and end datetime')

As of django-2.2, you can use constraints [Django-doc] in the Meta:

# since Django-2.2

from django.db import models
from django.db.models import F, Q
from django.db.models.functions import Now

class MyModel(models.Model):
    start = models.DateTimeField()
    end = models.DateTimeField()

    def clean(self):
        # ...
        pass

    class Meta:
        constraints = [
            models.CheckConstraint(
                check=Q(start__lte=F('end'), start__gte=Now()),
                name='correct_datetime'
            ),
        ]

Given the database system supports this, the constraints will be enforced at the database level as well.

like image 200
Willem Van Onsem Avatar answered Jan 30 '23 04:01

Willem Van Onsem