我正在使用Django模型形式,我想验证有效日期大于开始日期。这是我的代码,但是不起作用。我在form.py中使用了clean()方法,但是之后表单没有提交。
form.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])
model.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
答案 0 :(得分:0)
应该是
def clean(self):
cleaned_data = super().clean()
startdate = cleaned_data.get("startdate")
expiredate = cleaned_data.get("expiredate")
if startdate and enddate and ( expiredate < startdate ):
msg = u"expiredate should be greater than startdate."
raise forms.ValidationError(msg, code="invalid")
startdate and enddate and ( expiredate < startdate )
上方的代码用于防止TypeError
。当任何值均为None时。
答案 1 :(得分:0)
您可以参考official django docs来清洁多个字段。
像这样修复您的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."
)