Take the 2-minute tour ×
class Session(models.Model):
  tutor = models.ForeignKey(User)
  start_time = models.DateTimeField()
  end_time = models.DateTimeField()

What is the best way to always prevent start_time from overlapping end_time ?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

First, you should do this at the form level, see Cleaning and validating fields that depend on each other for instructions on how to do this, it would look like this:

def clean(self):
    cleaned_data = super(YourForm, self).clean()
    if cleaned_data['start_time'] > cleaned_data['end_time']:
        raise forms.ValidationError(_(u'Start time must be before end time'))

Also, you can enforce it at low level in the save method or in a pre_save signal:

from django.db.models import signals

class StartTimeAfterEndTimeException(Exception):
    def __init__(self, model):
        super(StartTimeAfterEndTimeException, self).__init__(
            'Start time %s should not be after end time %s' % (
                model.start_time, model.end_time))

def session_force_end_time(sender, instance, **kwargs):
    if instance.start_time >= instance.end_time:
        raise StartTimeAfterEndTimeException(instance)
signals.pre_save.connect(session_force_end_time, sender=Session)

But that's pretty low level so it's not user friendly.

share|improve this answer
At form level, I have to define this behavior for each form of my applications right ? –  Pierre de LESPINAY Mar 22 '12 at 11:14
You should define this behavior once and only once. You could define this behavior in SessionForm, and have other form classes for Session to inherit from SessionForm. –  jpic Mar 22 '12 at 11:16
Ok I see, I'll try to inherit forms. Thank you –  Pierre de LESPINAY Mar 22 '12 at 11:19

Your Answer


