Django - 重叠日期范围的表单验证

时间:2014-01-23 10:28:36

标签: python django django-forms django-validation

想象一下这个模型

class Session(models.Model):
    user = models.ForeignKey(User)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()

要添加/更新会话,我使用 modelForm

class SessionForm(forms.ModelForm):
    class Meta:
        model = Session
        fields = ('start_time', 'end_time',)

由于我需要阻止同一session的{​​{1}}重叠,因此我将此表格清理干净

user

但我正在def clean(self): cleaned_data = super(SessionForm, self).clean() start = cleaned_data.get('start_time') end = cleaned_data.get('end_time') conflicts = Session.objects.filter( start_time__lte=end, end_time__gte=start, ) if any(conflicts): raise forms.ValidationError(_("%i conflicts found" % conflicts.count())) return cleaned_data

之后添加user
save()

如何将其包含在冲突检查中?

换句话说,如何将if form.is_valid(): session = form.save(False) session.user = request.user session.save() 作为参数传递给user

1 个答案:

答案 0 :(得分:3)

可以替代覆盖__init__方法。在创建表单时,使用session集合传递user实例。

session = Session(user=request.user)
form = SessionForm(data=request.POST, instance=session)
if form.is_valid():
    form.save()

然后在您的干净方法中,您可以self.instance.user访问该用户。