对象不支持项目分配错误 [英] Object does not support item assignment error

查看:155
本文介绍了对象不支持项目分配错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 views.py 中,我在保存表单之前分配值。我以前用这样做:

In my views.py I assign values before saving the form. I used to do it the following way:

projectForm.lat = session_results['lat']
projectForm.lng = session_results['lng']

现在,由于变量列表有点长,我想通过以下循环来循环 session_results (如Adam here ):

Now, since the list of variables got a bit long, I wanted to loop over session_results with the following loop (as described by Adam here):

for k,v in session_results.iteritems():
    projectForm[k] = v

但是我收到错误项目对象不支持循环解决方案的项目分配。我有麻烦了解为什么。 项目是模型类,我用于ModelForm。

But I get the error 'Project' object does not support item assignment for the loop solution. I have trouble to understand why. Project is the model class, which I use for the ModelForm.

感谢您的帮助!

推荐答案

错误似乎很清楚:模型对象不支持项目分配。
MyModel.objects.latest('id')['foo'] ='bar'将抛出同样的错误。

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

这是一个有点混淆,你的模型实例被称为 projectForm ...

It's a little confusing that your model instance is called projectForm...

在循环中重现您的第一个代码块,您需要使用 setattr

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

这篇关于对象不支持项目分配错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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