Django 使用模型实例启动表单字段
我觉得这看起来很平常,并感到惊讶。
我拥有的
是 Django 模型 + 表单(ModelForm)。
我的用户填写了表单,在我看来,我有通常的情况:
if request.POST:
form = myForm(request.POST)
if request.method == "POST" and form.is_valid():
result = form.save(commit=False)
现在我需要大量操作表单的某些字段(在“结果”对象中),并且我想检查表单<保存之前再次 code>is_valid() 。
问题
我尝试使用字典(如建议的这里)
result_dictionary = dict((x.name, getattr(result, x.name)) for x in result._meta.fields)
或
result_dictionary = model_to_dict(result, fields=[field.name for field in result._meta.fields])
加上
testForm = myForm(initial=result_dictionary)
,但它没有通过 is_valid() 并且不会给出任何错误! 这些字段已正确传递到新表单...
有什么想法吗?
I thought it looks trivial, and was surprised.
What I have
I have a Django model + form (ModelForm).
My user fills in the form, and on my view I have the usual:
if request.POST:
form = myForm(request.POST)
if request.method == "POST" and form.is_valid():
result = form.save(commit=False)
Now I need to heavily manipulate some fields of the form (in the "result" object) and I want to check the forms is_valid()
again before saving.
The Problem
I tried to create a new form using the "result" object (that is a ModelForm object) using a dictionary (as suggested here)
result_dictionary = dict((x.name, getattr(result, x.name)) for x in result._meta.fields)
or
result_dictionary = model_to_dict(result, fields=[field.name for field in result._meta.fields])
plus
testForm = myForm(initial=result_dictionary)
but it doesn't pass is_valid() and does'nt give any errors!
The fields are passed OK to the new form...
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有时,查看 Django 源代码确实很有帮助,这里是
BaseForm.is_valid()
:因此,如果没有错误,
is_valid()
将返回 false,因为您没有绑定表单后,您还没有在任何地方提供表单来查找数据。尝试使用form.data
字典,如下所示:Sometimes, looking in the Django source can be really helpful, here's
BaseForm.is_valid()
:So if there are no errors,
is_valid()
returns false because you haven't bound the form, you haven't given the form anywhere to look for data. Try using theform.data
dictionary instead, something like this: