Django:如何将 DateField 设置为仅接受 Today &未来日期 [英] Django: How to set DateField to only accept Today & Future dates

查看:31
本文介绍了Django:如何将 DateField 设置为仅接受 Today &未来日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

推荐答案

你可以在你的表单中添加一个 clean() 方法来确保日期不是过去的.

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

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

这篇关于Django:如何将 DateField 设置为仅接受 Today &amp;未来日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆