2

想象一下这个模型

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相同的 suser重叠,所以我把这个表格弄干净了

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作为参数传递给clean()

4

1 回答 1

3

有一种替代方法可以覆盖该__init__方法。创建表单时传递session带有集合的实例。user

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

然后在您的 clean 方法中,您可以将用户访问为self.instance.user.

于 2014-01-23T11:03:29.210 回答