Object does not support item assignment error

PythonDjangoLoopsDictionary

Python Problem Overview


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

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.

Thank you for your help!

Python Solutions


Solution 1 - Python

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

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

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)

Solution 2 - Python

Another way would be adding __getitem__, __setitem__ function

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

You can use self[key] to access now.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionneurixView Question on Stackoverflow
Solution 1 - PythonYuji 'Tomita' TomitaView Answer on Stackoverflow
Solution 2 - PythonIvan WangView Answer on Stackoverflow