django - 如何验证过期日期大于 Django 模型表单中的开始日期
问题描述
我正在使用 Django 模型表单,我想验证到期日期是否大于开始日期。这是我的代码,但它不起作用。我在 form.py 中使用了 clean() 方法,但之后表单没有提交。
表格.py
class CertificateForm(forms.ModelForm):
app_attributes = {'oninvalid': 'this.setCustomValidity("Application field is required")', 'oninput': 'this.setCustomValidity("")'}
startdate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100)))
expiredate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100)))
application = forms.CharField(widget=forms.TextInput(attrs=app_attributes))
File= forms.FileField(required=True)
class Meta:
model = certificateDb
fields = ('application', 'startdate', 'expiredate', 'environment_type','File' )
error_messages = {
'application': {
'required': ("Application field is required"),
},
}
def clean(self):
startdate = cleaned_data.get("startdate")
expiredate = cleaned_data.get("expiredate")
if expiredate < startdate:
msg = u"expiredate should be greater than startdate."
self._errors["expiredate"] = self.error_class([msg])
模型.py
class certificateDb(models.Model):
Dev = 1
QA = 2
UAT = 3
Production = 4
environment_TYPES = ( (Dev, 'Dev'), (QA, 'QA'), (UAT, 'UAT'), (Production, 'Production'), )
application = models.CharField(db_column='Application', max_length=255, blank=True, null=True) # Field name made lowercase.
startdate = models.DateField(null=True)
expiredate = models.DateField(null=True)
environment_type = models.PositiveSmallIntegerField(choices=environment_TYPES)
File = models.FileField(upload_to='CSR/', null=True , blank = True)
def __str__(self):
return self.application
解决方案
您可以参考官方 django 文档了解如何清理多个字段。
像这样修复你的clean
方法:
def clean(self):
cleaned_data = super().clean()
startdate = cleaned_data.get("startdate")
expiredate = cleaned_data.get("expiredate")
if startdate and expiredate and expiredate < startdate:
raise forms.ValidationError(
"Expiredate should be greater than startdate."
)
推荐阅读
- r - rmarkdown 中的自定义突出显示样式
- python - 将变量分配给值的一部分
- html - 在 Angular 中,如何获取具有可扩展内容的 Mat-Table 上的行索引?
- python-3.x - 获取 urllib HTTP 错误 401 未经授权
- javascript - Google 表格:执行自定义功能时出现内部错误
- process - 绘制到 HelixViewPort3D 时出现 System.InvalidOperationException
- mp4 - 格式化 AVC/H.264 mdat
- time-complexity - 在没有指数膨胀的情况下将类型和值缩小在一起
- php - pecl 在 mac 上安装 mongodb,致命错误:找不到“Security/Security.h”文件
- ios - Xamarin ios 云文件复制位置问题