为什么执行form.is_valid()会导致删除不在Django表单中的实例字段? [英] Why executing form.is_valid() cause deleting of the instance fields that aren't in the form in django?
问题描述
假设此视图用于编辑记录:
Suppose this view that is for edit record:
def edit_post(request, slug):
post = get_object_or_404(Post, slug=slug)
if request.method == "POST":
form = AddPostForm(request.POST, request.FILES, instance=post)
# 1
if form.is_valid():
# 2
new_post = form.save(commit=False)
new_post.save()
return redirect('administrator:view_admin_post')
...
现在假设这些:
-
我具有
POST
模型中存在的field1
.
field1
具有默认值,并假定
field1
取决于先前.
field1
has default value and suppose that the current value of
field1
depends on previous.
在这种情况下,当我在# 1
行中写入print(post.field1)
时,我具有先前的值,但是当我在其中打印时
行# 2
我得到了None
!
In this situation when I write print(post.field1)
In line # 1
I have previous value but when I print that in
line # 2
I got None
!
这是怎么回事?我怎么能得到我的post.field1
?
What is going on?And how can I have my post.field1
?
注意:我知道我可以定义一个中间件变量并将以前的值保存在该变量中.但是有更好的方法吗?
Notice: I know I can define a middleware variable and save the previous value in this variable.But is there a better way to do this?
推荐答案
第一点:.is_valid()
不会涉及您的数据库(除非您自定义表单的验证,但是,那么,您将知道为什么使用xD).是Model.save()
的调用(直接或通过form.save()
)覆盖了先前的值.
First point: .is_valid()
will NOT touch your database (unless you customize the form's validation, but then, well, you'd know why xD). It's the call to Model.save()
(either directly or thru form.save()
) that overwrites the previous value.
第二点:如果将模型实例传递给表单(这是您要执行的操作),则可以通过模板中的{{ form.instance.your_field_name }}
访问它(及其字段).
Second point: if you pass a model instance to your form (which is what you do), you can access it (and it's fields) thru {{ form.instance.your_field_name }}
in the template.
最后,您可以从ModelForm中完全排除模型字段,也可以将其标记为只读.
And finally, you can either totally exclude a model field from the ModelForm, or mark it as read-only.
所有这些都已被FWIW充分记录,因此,我建议您花一些时间阅读文档,然后再进行离奇而又费解的解决方案"(提示:您绝对不需要中间件来获得原始价值. ,它仍然在您的数据库中-直到您覆盖它为止.
All of this is rather well documented FWIW, so I kindly suggest you take some time reading the doc before going any further with bizarre and convoluted "solutions" (hint: you definitly don't need a middleware to get the original value, it's still in your database - until you overwrite it, that is).
这篇关于为什么执行form.is_valid()会导致删除不在Django表单中的实例字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!