我试图在哪里引发验证错误:
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)