django表单保存不能用于更新模型实例?

时间:2016-02-17 03:52:24

标签: django django-forms

我正在使用django 1.8.4

djanog.forms.models.BaseModelForm.save读取如下

save_instance

def save_instance(form, instance, fields=None, fail_message='saved', commit=True, exclude=None, construct=True): """ Saves bound Form ``form``'s cleaned_data into model instance ``instance``. If commit=True, then the changes to ``instance`` will be saved to the database. Returns ``instance``. If construct=False, assume ``instance`` has already been constructed and just needs to be saved. """ if construct: instance = construct_instance(form, instance, fields, exclude) 有这个..

construct = True

基本上,上面的代码(save_instance)仅在construct = False时更新实例,但django代码始终通过filterEvensMap = \fn items -> map fn (filter isEven items)

这是1.8.4中的错误吗? :(

我刚检查代码保持不变,直到1.8.9

1 个答案:

答案 0 :(得分:1)

construct_instance中调用BaseModelForm._post_clean方法:

# BaseModelForm._post_clean()
# Update the model instance with self.cleaned_data.
self.instance = construct_instance(self, self.instance, opts.fields, construct_instance_exclude)

调用此函数时,您的"实例"将使用表单数据进行更新。

请注意_post_clean作为BaseForm.full_clean的一部分进行调用,通常由is_valid间接调用。这意味着如果您不验证表单,则调用save方法将失败并显示新实例,或者无法更新旧实例。