[英]initialising a form with data using django on google appengine
I have a post handler that uses a 'from google.appengine.ext.db.djangoforms.ModelForm'.我有一个使用“来自 google.appengine.ext.db.djangoforms.ModelForm”的帖子处理程序。 It pulls the existing instance the data base then initialises the form by:
它将现有实例拉入数据库,然后通过以下方式初始化表单:
myForm = TestForm(instance=self_instance, data=post_data)
I'm only putting one of the three properties in the post_data which is being correctly copied to the form but the other two properties which already have values in the 'self_instance' are being set to None.我只将三个属性之一放在 post_data 中,该属性已正确复制到表单中,但其他两个在“self_instance”中已有值的属性被设置为无。 Can this be avoided?
这可以避免吗?
Thanks, Richard谢谢,理查德
This is giving me the behaviour I'm after:这给了我我所追求的行为:
if self_instance:
logging.info('creating form with instance so updating the post data, we need this to bind the form so we can validate it')
if post_data:
#update the post data with existing values
for prop in self_instance._properties:
if prop not in post_data:
cur_prop_val = getattr(self_instance, prop)
if isinstance(cur_prop_val,db.Model):
str(cur_prop_val.key())
else:
post_data[prop] = cur_prop_val
else:
logging.info('no post data so not adding it to form')
form_data = form_class(data=post_data,instance=self_instance)
else:
logging.info('creating form without instance')
form_data = form_class(data=post_data)
You don't show your form definition.您没有显示您的表单定义。 But, generally, if you don't want to include fields in the form, you should specify them in the Meta
exclude
tuple - then they won't be overwritten by non-existent POST data.但是,一般来说,如果您不想在表单中包含字段,您应该在 Meta
exclude
元组中指定它们 - 这样它们就不会被不存在的 POST 数据覆盖。
instance
arg, the form is considered unboundinstance
arg,则该表单被视为未绑定data
arg, the form is considered bounddata
arg,则该表单被视为已绑定If you supply both, data
will override instance
(=> same as case 2, form bound).如果两者都提供,
data
将覆盖instance
(=> 与案例 2 相同,表单绑定)。
So in your case, it's better to load self_instance
then update it with data
and then use the unbound form:所以在你的情况下,最好加载
self_instance
然后用data
更新它,然后使用未绑定的表单:
myForm = TestForm(instance=self_instance)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.