对象不支持项目分配错误
在我的 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)