Django:如何将DateField设置为仅接受今天和未来日期

Emi*_*ile 18 python django django-forms datefield

我一直在寻找方法将我的Django表单设置为仅接受今天或未来的日期.我目前在前端有一个jQuery datepicker,但这里是一个modelform的表单字段.

感谢您的帮助,非常感谢.

date = forms.DateField(
    label=_("What day?"),
    widget=forms.TextInput(),
    required=True)
Run Code Online (Sandbox Code Playgroud)

Arn*_*aud 30

您可以clean()在表单中添加方法,以确保日期不是过去的日期.

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
Run Code Online (Sandbox Code Playgroud)

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

  • 如果“date &lt; datetime.today():”引发 Typeerror,则您的答案中有一个错误。它应该是:“from datetime import date”//“if date &lt; date.today():”但是再次感谢,一个很大的帮助 (2认同)

小智 7

另一个有用的解决方案是使用validators关键字参数将验证绑定到字段.这是保持表单代码清晰并允许重用验证逻辑的便捷方法.例如

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])
Run Code Online (Sandbox Code Playgroud)