Avoid Booking past dates with django

Solution 1:

You can add an extra validation to the date fields like this:

from django.utils import timezone


class AvailabilityForm(forms.Form): 
    # ... the fields

    def clean_start_time(self)
        start = self.cleaned_data.get('start_time')
        if start < timezone.now():
            raise forms.ValidationError('the date must be after now.')
        return data

Can se more at https://docs.djangoproject.com/en/4.0/ref/forms/validation/#cleaning-a-specific-field-attribute

Next, you need little rewrite your view and send the form to the template in order to display these errors, like explained in this docs:

  • https://docs.djangoproject.com/es/4.0/topics/forms/#the-view
  • https://docs.djangoproject.com/es/4.0/topics/forms/#the-template