Django: How to set DateField to only accept Today & Future dates
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
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])