Django:如何将 DateField 设置为仅接受“今天”和“今天”未来日期
我一直在寻找方法将 Django 表单设置为仅接受今天或未来几天的日期。我目前在前端有一个 jQuery 日期选择器,但这里是模型表单的表单字段。
感谢您的帮助,非常感谢。
date = forms.DateField(
label=_("What day?"),
widget=forms.TextInput(),
required=True)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在表单中添加
clean()
方法以确保日期不是过去的日期。请参阅http://docs.djangoproject.com/en/ dev/ref/forms/validation/#cleaning-a-specific-field-attribute
You could add a
clean()
method in your form to ensure that the date is not in the past.See http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute
另一个有用的解决方案是使用 validators 关键字参数将验证与字段联系起来。这是保持表单代码清晰并允许重用验证逻辑的便捷方法。例如
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
发现 MinValueValidator 也非常适合日期。
Found out MinValueValidator works perfectly for dates as well.
如果您使用的是 Django 1.2+ 并且您的模型将始终强制执行此规则,您还可以查看 模型验证。优点是任何基于模型的模型都会自动使用此验证。
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.