23

I have been looking for ways to set my Django form to only accept dates that are today or days in the future. I currently have a jQuery datepicker on the frontend, but here is the form field to a modelform.

Thanks for the help, much appreciated.

date = forms.DateField(
    label=_("What day?"),
    widget=forms.TextInput(),
    required=True)
Emile
  • 3,464
  • 8
  • 46
  • 77

4 Answers4

35

You could add a clean() method in your form to ensure that the date is not in the past.

import datetime

class MyForm(forms.Form):
    date = forms.DateField(...)

    def clean_date(self):
        date = self.cleaned_data['date']
        if date < datetime.date.today():
            raise forms.ValidationError("The date cannot be in the past!")
        return date

See http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute

Arnaud
  • 1,785
  • 18
  • 22
  • 2
    There is a bug in your answer, if "date < datetime.today():" raises a Typeerror. It should be: "from datetime import date" // "if date < date.today():" But thanks again, a big help – Emile Feb 09 '11 at 17:22
  • Sorry about that, I fixed it. – Arnaud Feb 09 '11 at 21:50
10

Another useful solution is to tie validation to fields using the validators keyword argument. This is a handy way of keeping your Form code clear and enabling reuse of validation logic. For e.g

def present_or_future_date(value):
    if value < datetime.date.today():
        raise forms.ValidationError("The date cannot be in the past!")
    return value

class MyForm(forms.Form):
    date = forms.DateField(...
                           validators=[present_or_future_date])
daramcq
  • 174
  • 2
  • 6
3

Found out MinValueValidator works perfectly for dates as well.

import datetime
from django.core.validators import MinValueValidator
from django.db import models

...

some_date = models.DateField(validators=[MinValueValidator(datetime.date.today)])
Dmytro O
  • 406
  • 5
  • 11
2

If you are using Django 1.2+ and your model will always force this rule, you can also take a look at model validation. The advantage will be that any modelform based on the model will use this validation automatically.

shanyu
  • 9,536
  • 7
  • 60
  • 68