目前,我的模型表单覆盖了save()方法,它工作正常。问题是当我调用savedObject = form.save()时,表单被保存但是它返回None?在覆盖save()之前,我会得到保存的对象,但这种方法有什么问题?
以模型形式保存():
def save(self, *args, **kwargs):
kwargs['commit']=False
obj = super(MyForm, self).save(*args, **kwargs)
obj.time = datetime.date.today()
obj.expire = datetime.date.today()
return obj.save()
在POST之后在我的视图中调用:
savedObject = form.save()
#form is now saved, but savedObject is None
答案 0 :(得分:6)
正确的方法:
def save(self, commit=True):
obj = super(MyForm, self).save(commit=False)
obj.time = datetime.date.today()
obj.expire = datetime.date.today()
if commit:
obj.save()
return obj