想象一下这个模型
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()
?