django - 表单ValidationError无法正常工作

时间:2017-08-15 11:26:16

标签: python django django-forms validationerror

我正在尝试提出验证错误,其中:

1)如果在start_date字段中选择的日期是今天的前一天,则会引发错误。当我提交它时抛出此错误

  

'<' 'NoneType'和'datetime.date'实例之间不支持

2)如果结束日期是开始日期之前的日期,则会引发另一个错误。对于这部分,它部分工作,我不保存提交的表单,但它不会引发和验证错误

我知道这不是第一次有人提出这个问题,但是我按照其他人给出的答案而且它不起作用,我做错了什么?

任何帮助都非常感谢。

以下是我的代码:

model.py:

class Leave(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='+')
    start_date = models.DateField()
    end_date = models.DateField()
    duration = models.FloatField()

form.py:

class LeavesDetailForm(forms.ModelForm):

    class Meta:
        model = Leave
        fields = ('employee', 'type', 'status', 'start_date', 'end_date', 'duration', 'comment')
        widgets = {'start_date': forms.DateInput(attrs={'type': 'date'}),
                   'end_date': forms.DateInput(attrs={'type': 'date'}),
                   'employee': forms.HiddenInput(),
                   'duration': forms.HiddenInput(),
                   'status': forms.HiddenInput()}

    def clean(self):
        start_date = self.cleaned_data.get("start_date")
        end_date = self.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])
        raise forms.ValidationError("End date should be greater than start date.!")

    def clean_start_date(self):
        start_date = self.cleaned_data.get('start_date')
        if self.instance.start_date < datetime.date.today():
            raise forms.ValidationError("The date cannot be in the past!")
        return start_date

view.py:

def my_leaves_view(request):
    form = LeavesDetailForm(request.POST or None)
    leaves_log = Leave.objects.all().filter(employee=request.user.profile.employee.id)
        if form.is_valid():
        inst = form.save(commit=False)
        inst.start_date = form.cleaned_data['start_date']
        inst.end_date = form.cleaned_data['end_date']
        duration = (inst.end_date - inst.start_date).days
        inst.duration = duration
        inst.save()
        return HttpResponseRedirect('my_leaves_content.html')
    context = {'form': form}
    return render(request, 'hrm/my_leaves/my_leaves_content.html', context)

2 个答案:

答案 0 :(得分:0)

看起来你刚才错误地命名了这个函数。将clean_date更改为clean_start_date,因为它应采用clean_function_name格式。

希望它有所帮助!

答案 1 :(得分:0)

如果用户未提交有效日期,则在clean方法中,start_dateend_date可能为None

正如错误所示,Python不允许您将date实例与None进行比较。

在比较之前,您应该检查自cleaned_data的有效日期:

if end_date is not None and start_date is not None and end_date < start_date:

clean_start_date方法中,您应该使用从start_date获取的cleaned_data,而不是self.instance.start_date

def clean_start_date(self):
    start_date = self.cleaned_data.get('start_date')
    if start_date < datetime.date.today():
        raise forms.ValidationError("The date cannot be in the past!")
    return start_date