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
小智 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)
| 归档时间: |
|
| 查看次数: |
11326 次 |
| 最近记录: |