将未绑定的表单转换为绑定形式? [英] Transform an unbound form to a bound one?

查看:116
本文介绍了将未绑定的表单转换为绑定形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个对象的绑定表单来使用is_valid方法。原因是因为我有一些旧数据,我希望用户根据新的验证规则进行更正。然后,我想以我的形式重用清洁方法的代码。



我最后序列化了我的回复:



来自django.utils的$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $



fields_dict = simplejson.loads(serialize('json',[obj]))[0] ['fields']
form = forms.MyForm(fields_dict)
如果form.is_valid

这个工作,但似乎并不像Djangish那样。另外,它似乎是一个常见的问题,所以我正在寻找一个更好的方法来做到这一点。



根据文档翻译数据从unbound到unbound并不意味着发生:
https://docs.djangoproject.com/en/ dev / topics / forms / modelforms /#the-save-method
但是,这将是我最简单的解决方案。

解决方案

有Django的 django.forms.models.model_to_dict 函数,它将把现有的模型实例转换为适合绑定到 ModelForm



这可能会更有效,而且比串行化和非串行化对象更为Djangish。



如果您还使用实例关键字创建表单,则会在保存时更新现有记录



所以:

  from django.forms.models import model_to_dict 

...

fields_dict = model_to_dict(obj)
form = forms.MyForm(fields_dict,instance = obj)


I want to have a bound form from an object to use the is_valid method. The reason is because I have some old data that I want the users to correct according to the new validation rules. Then, I want to reuse the code of the clean methods in my form.

I ended up serializing my response:

from django.utils import simplejson
from django.core.serializers import serialize

(...)

fields_dict = simplejson.loads(serialize('json', [obj]))[0]['fields']
form = forms.MyForm(fields_dict)
if form.is_valid

This works but it doesn't seem very Djangish. Also, it seems as a common problem so I was looking for a better way of doing this.

According to the documentation translate data from unbound to unbound is not meant to happen: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method However, that would be the easiest solution for me.

解决方案

There is Django's django.forms.models.model_to_dict function that will convert your existing model instance into a dictionary of data suitable for binding to a ModelForm.

This would probably be more efficient, and definitely more "Djangish", than serialising and unserialising the object.

And if you also create the form with the instance keyword, it will know to update the existing record when saved.

So:

from django.forms.models import model_to_dict

...

fields_dict = model_to_dict(obj)
form = forms.MyForm(fields_dict, instance=obj)

这篇关于将未绑定的表单转换为绑定形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆