Bob Reynolds
Bob Reynolds

Reputation: 91

Why does Django return Django object is not iterable error?

What am i getting this error for ?

models.py

class Category(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name


class SubCategory(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    image_url = models.CharField(default=0, max_length=2000)
    price = models.IntegerField(default=0)

views.py

def category(request, pk):
    categories = Category.objects.get(id=pk)
    subcategories = SubCategory.objects.filter(category=categories)
    return render(request, 'category.html', {'categories': categories, 'subcategories': subcategories})

urls.py

urlpatterns = [
    path('', views.index),
    url(r'^category/(?P<pk>\d+)$', views.category, name='category'),
]

base.html

{% for category in categories %}
<a class="dropdown-item" href="{% url 'category' pk=category.id %}">{{ category.name }}</a>
{% endfor %}

Upvotes: 2

Views: 835

Answers (3)

Bob Reynolds
Bob Reynolds

Reputation: 91

because, my error was related with queryset. what does it mean ? an array. and each array has its indexes, so, in this example, our 'categories' is an array and we must assign its first ([0]) index to a category:

def category(request, pk):
        categories = Category.objects.get(id=pk)
        subcategories = SubCategory.objects.filter(category=categories[0])
        return render(request, 'category.html', {'categories': categories, 'subcategories': subcategories})

Upvotes: 0

Devang Padhiyar
Devang Padhiyar

Reputation: 3697

You are trying to get only one Category object in below file.

views.py

def category(request, pk):
        categories = Category.objects.get(id=pk) # Here you trying to get category
        subcategories = SubCategory.objects.filter(category=categories)
        return render(request, 'category.html', {
            'categories': categories, # categories is single object not iterable
            'subcategories': subcategories})

For solution you can either set categories = Category.objects.filter(id=pk) to your views.py or update your html template.

Upvotes: 0

user2390182
user2390182

Reputation: 73450

get returns a model instance, not a queryset (despite your misleading variable name):

categories = Category.objects.get(id=pk)  # instance, not queryset!

Hence:

{% for category in categories %}  # instance cannot be looped over!

produces the error that you encoutered.

Upvotes: 2

Related Questions