在Django Model Form中,验证end_date大于start_date

时间:2011-09-08 22:47:36

标签: python django validation modelform

我的模型中有一个start_date和end_date字段,当它比start_date大时,我想给end_date分配一个错误,我一直在寻找文档,但是没有找到关于它的例子。

3 个答案:

答案 0 :(得分:9)

您需要在表单中使用自定义清理功能进行检查:

def clean(self):
    start_date = cleaned_data.get("start_date")
    end_date = cleaned_data.get("end_date")
    if end_date < start_date:
        msg = u"End date should be greater than start date."
        self._errors["end_date"] = self.error_class([msg])

答案 1 :(得分:0)

这是docs

中的实际推荐示例

简而言之,请记住返回cleaning_data,并正确引发表单错误。

from django import forms

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean_recipients(self):
        data = self.cleaned_data['recipients']
        if "fred@example.com" not in data:
            raise forms.ValidationError("You have forgotten about Fred!")

    # Always return the cleaned data, whether you have changed it or
    # not.
    return data

答案 2 :(得分:0)

这是Django 2.2的更新-doc

from django import forms
from .models import Project

class ProjectAddForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = [
            'name', 
            'overview',
            'start_date',
            'end_date',
            'status',
            'completed_on',
        ]

        labels = {
            "name": "Project Name",
            "overview": "Project Overview",
            "status": "Project Status",
        }

    # Logic for raising error if end_date < start_date
    def clean(self):
        cleaned_data = super().clean()
        start_date = cleaned_data.get("start_date")
        end_date = cleaned_data.get("end_date")
        if end_date < start_date:
            raise forms.ValidationError("End date should be greater than start date.")