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()
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.
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.
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.
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 // … }
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'})
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With