TypeError object is not iterable in Django

Viewed 1026

I am creating a movie site using Django. I have created a Genre model in it and displayed it in the template. Now i want those each genre objects to redirect to some other page. For example i have created 45 genre types and displayed in the template. Now what i want to do is, redirect user to for example Action genre list when clicked on Genre Action in the template. For that i used for loop in template but when clicked in any of the genre objects it throws TypeError at /home/genre/5/ 'Genre' object is not iterable. What is the problem here? Any suggestions will be great.

my urls.py:

urlapatterns = [path('', views.home, name='home'), path('genre/<int:pk>, views.genreView, name='home')]

views.py:

def genreView(request, pk):
genres = get_object_or_404(Genre, id=pk)
context = {
    'genres': genres
}

return render(request, 'genre.html', context)

def home(request):
genres = Genre.objects.all()
context = {
    'genres': genres
}

return render(request, 'index.html', context)

home.html:

{% for genre in genres %}
  <a href="{% url 'genre' genre.id %}" class="text-yellow-400 hover:text-white p-2 text-xs">{{genre.title}}</a>     
{% endfor %}

models.py:

 class Genre(models.Model):
    title = models.CharField(max_length=500)

def __str__(self):
    return self.title
1 Answers

In your view, genres is not a QuerySet (collection) of Genres, but a single Genre object, you thus should simply render the details of that genre:

def genreView(request, pk):
    genre = get_object_or_404(Genre, id=pk)
    context = {
        'genre': genre
    }
    return render(request, 'genre.html', context)

and in your genre.html you should not iterate over the genre, but render this like:

<!-- genre.html -->
<!-- do not iterate over genre -->

{{ genre.title }}
<!-- … -->
Related