Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object does not support item assignment error

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!

like image 726
neurix Avatar asked Dec 17 '11 03:12

neurix


People also ask

How do I fix int object does not support item assignment?

The Python "TypeError: 'int' object does not support item assignment" occurs when we try to assign a value to an integer using square brackets. To solve the error, correct the assignment or the accessor, as we can't mutate an integer value.

Do python sets support item assignment?

The Python "TypeError: 'set' object does not support item assignment" occurs when we try to change the value of a specific item in a set. If you meant to declare a list, use square brackets instead of curly braces, e.g. my_list = [] .

How do I fix str object does not support item assignment in Python?

The Python "TypeError: 'str' object does not support item assignment" occurs when we try to modify a character in a string. Strings are immutable in Python, so we have to convert the string to a list, replace the list item and join the list elements into a string.

Does set support item assignment?

In Python, you cannot access the elements of sets using indexing. If you try to change a set in place using the indexing operator [], you will raise the TypeError: 'set' object does not support item assignment. This error can occur when incorrectly defining a dictionary without colons separating the keys and values.


1 Answers

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) 
like image 97
Yuji 'Tomita' Tomita Avatar answered Oct 05 '22 16:10

Yuji 'Tomita' Tomita