Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to set DateField to only accept Today & Future dates

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)
like image 202
Emile Avatar asked Feb 09 '11 06:02

Emile


3 Answers

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

like image 187
Arnaud Avatar answered Nov 11 '22 21:11

Arnaud


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])
like image 45
daramcq Avatar answered Nov 11 '22 23:11

daramcq


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.

like image 2
shanyu Avatar answered Nov 11 '22 22:11

shanyu