Ömer
Ömer

Reputation: 39

How do I check if the end date is not before the start date django

I need to check that the end date of the event is not before the start date

class Event(models.Model):
    name = models.CharField(max_length=100)
    start_date = models.DateField()
    end_date = models.DateField()
    session=models.ForeignKey(Session,on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, editable=False, max_length=100)

Upvotes: 0

Views: 1168

Answers (1)

Sazzy
Sazzy

Reputation: 1994

I would advise to look into signals in Django. See URL: https://docs.djangoproject.com/en/3.0/ref/signals/#pre-save

Here is a draft (untested) example you can try:

from django.db.models.signals import pre_save

class Event(models.Model):
    name = models.CharField(max_length=100)
    start_date = models.DateField()
    end_date = models.DateField()
    session=models.ForeignKey(Session,on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, editable=False, max_length=100)


def check_date(sender, instance, *args, **kwargs):
    if instance.start_date > instance.end_date:
        raise ValueError('Start date must be less than end date')

pre_save.connect(check_date, sender=Event)

When saving with incorrect dates an error should be raised.

Upvotes: 2

Related Questions