0

我试图在哪里引发验证错误:

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

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

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

我知道这不是第一次有人问这个问题,但我遵循了其他人给出的答案,但它不起作用,我哪里做错了?

非常感谢任何帮助。

下面是我的代码:

模型.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()

表格.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

视图.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)
4

2 回答 2

0

看起来你只是把函数命名错了。更改clean_dateclean_start_date应采用的格式clean_function_name

希望能帮助到你!

于 2017-08-15T11:28:37.827 回答
0

在该clean方法中,start_date或者end_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
于 2017-08-15T13:17:46.943 回答