对象不支持项分配错误

时间:2022-03-10 00:32:27

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']

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):

现在,由于变量列表有点长,我想用下面的循环对session_results进行循环(如Adam在这里所描述的):

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

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.

但是我得到错误的'Project'对象不支持循环解决方案的项分配。我不明白为什么。Project是model类,我将它用于ModelForm。

Thank you for your help!

谢谢你的帮助!

2 个解决方案

#1


48  

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

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

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

您的模型实例被称为projectForm,这有点令人困惑。

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

要在循环中复制第一个代码块,需要使用setattr

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

#2


12  

Another way would be adding __getitem__, __setitem__ function

另一种方法是增加__getitem__, __setitem__函数。

def __getitem__(self, key):
    return getattr(self, key)

You can use self[key] to access now.

现在可以使用self[key]访问。

#1


48  

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

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

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

您的模型实例被称为projectForm,这有点令人困惑。

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

要在循环中复制第一个代码块,需要使用setattr

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

#2


12  

Another way would be adding __getitem__, __setitem__ function

另一种方法是增加__getitem__, __setitem__函数。

def __getitem__(self, key):
    return getattr(self, key)

You can use self[key] to access now.

现在可以使用self[key]访问。