【发布时间】:2012-09-09 02:34:21
【问题描述】:
我是 Django 新手,对表单处理期间的验证步骤有些困惑。我知道默认情况下需要所有表单字段类型(在我的情况下为 ModelForm)。我假设 Django 会引发 VaidationError 以防必填表单字段留空没有调用表单的 clean 方法。
这就是为什么我没有检查以下clean()方法中是否设置了任何数据:
def clean(self):
date = self.cleaned_data.get('date')
time_start = self.cleaned_data.get('time_start')
time_end = self.cleaned_data.get('time_end')
user_type = self.cleaned_data.get('user_type')
if Event.objects.filter(user_type=user_type, date=date,
time_start__lt=time_start,
time_end__gt=time_start).exclude(pk=self.instance.pk).count():
raise forms.ValidationError("Overlapping with another event.")
提交表单时将所有字段留空会导致
ValueError: 不能使用 None 作为查询值。
如果我删除我的 clean() 方法,我将得到预期的 ValidationErrors,因为没有填写必填字段 - 这是我在 clean() 方法仍然存在时所期望的。
知道什么会导致这种情况发生吗?如果 Django 在调用 clean 之前 不检查所需的值,我会感到惊讶。
【问题讨论】:
标签: django forms validation