首页 > 解决方案 > 如何验证过期日期大于 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

标签: djangodjango-modelsdjango-forms

解决方案


您可以参考官方 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."
                )

推荐阅读