Django:如何设置DateField只接受Today&未来日期 [英] Django: How to set DateField to only accept Today & Future dates
本文介绍了Django:如何设置DateField只接受Today&未来日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在寻找方法来设置我的Django表单,只接受今天或几天的日期。我目前在前端有一个jQuery datepicker,但这里是一个modelform的表单域。
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&未来日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文