如何防止 Django 接受无效日期并转换它们?
我有以下形式:
class GuaranteesForm(forms.ModelForm):
birth_date = forms.DateField(input_formats=['%d/%m/%Y'], required=True)
但是,如果用户插入无效日期,例如:13/13/1999,Django 不会引发异常,而是通过执行日期和月份字段的模数并相应地添加月份和年份来转换日期。在示例中,由于月份大于 12,因此保留的日期将为 13/01/2000。
我宁愿得到 InvalidFormException,有什么办法可以防止这种行为吗?
我在 Jython (DOJ) 上使用 Django。
我已经通过 clean_birth_date 实现了一个解决方案,但我认为它相当丑陋。我正在寻找一种方法来防止这种约会行为。
I have the following Form:
class GuaranteesForm(forms.ModelForm):
birth_date = forms.DateField(input_formats=['%d/%m/%Y'], required=True)
However if the user inserts an invalid date like: 13/13/1999 instead of raising an exception, Django converts the date by performing modulus of the day and month fields, and adding months and years accodingly. In the example, since the month is above 12, the Date which would get persisted would be 13/01/2000.
I'd much rather get an InvalidFormException, is there any way to prevent this behaviour?
I'm using Django on Jython (DOJ).
I've already implemented a solution through clean_birth_date, but I think it's rather ugly. What I'm looking for is a way to prevent this kind of behaviour with dates in general.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在清理时手动引发异常特定的表单字段。
You can rise an exception manually when cleaning a specific form field.