5

目前,我的模型表单正在覆盖 save() 方法,并且工作正常。问题是当我调用 savedObject = form.save() 时,表单被保存但它返回 None?在覆盖 save() 之前,我会得到保存的对象,但是这种方法有什么问题?

模型形式的 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
4

1 回答 1

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
于 2013-03-03T09:27:26.170 回答