Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an object is not iterable error?

Tags:

django

Why do I get the following error in my app

Caught TypeError while rendering: 'ModelNameHere' object is not iterable

but I don't get it when I execute it from the shell?

I just have a custom field in my form which inherits from forms.ModelForm

custom_serving_size = forms.ChoiceField(
    ServingSize.objects.all(),
    widget=forms.Select(attrs={'class':'ddl'})
)

EDIT

This is my form class

class RecipeIngredientForm(forms.ModelForm):
    serving_size = forms.ChoiceField(choices=ServingSize.objects.all())

The error happens on ServingSize.objects.all()

like image 606
iJK Avatar asked Aug 07 '10 04:08

iJK


People also ask

How do I fix an object is not iterable in Python?

The Python TypeError: NoneType Object Is Not Iterable error can be avoided by checking if a value is None or not before iterating over it. This can help ensure that only objects that have a value are iterated over, which avoids the error.

What is not iterable in Python?

While programming in Python, it is a common practice to use loops such as for loops and while loops. These are used for iterating over lists and dictionaries for performing a variety of operations on the elements.

How do you make an object iterable in Python?

To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__() , which allows you to do some initializing when the object is being created.

Why are objects not iterable in JavaScript?

In JavaScript, Object s are not iterable unless they implement the iterable protocol. Therefore, you cannot use for...of to iterate over the properties of an object. const obj = { France: 'Paris', England: 'London' }; for (const p of obj) { // TypeError: obj is not iterable // … }


1 Answers

custom_serving_size = forms.ChoiceField(
    ServingSize.objects.all(),
    widget=forms.Select(attrs={'class':'ddl'})
)

this has to be

custom_serving_size = forms.ModelChoiceField(
    queryset=ServingSize.objects.all(),
    widget=forms.Select(attrs={'class':'ddl'})
)

or

custom_serving_size = forms.ChoiceField(
    choices=[(obj.id, `text user sees`) for obj in ServingSize.objects.all()],
    widget=forms.Select(attrs={'class':'ddl'})
)
like image 116
Ashok Avatar answered Oct 11 '22 23:10

Ashok