0

I am following along an online Python tutorial and I am have to create an HTML template in which creates a table for the end user to see the movies in the inventory. I have followed the teachers instructions step-by-by step but when I refresh the browser page, it only shows the class attributes that I listed in the HTML. The code that I wrote is below:

index.html file:

<table class="table">
    <thead>
        <tr>
            <th>Title</th>
            <th>Genre</th>
            <th>Stock</th>
            <th>Daily Rate</th>
        </tr>
    </thead>
    <tbody>
        {% for movie in movies %}
            <tr>
                <td>{{ movie.title }}</td>
                <td>{{ movie.genre }}</td>
                <td>{{ movie.number_in_stock }}</td>
                <td>{{ movie.daily_rate }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>

and the views.py file:

from django.http import HttpResponse
from django.shortcuts import render
from .models import Movie


def index(request):
    movies = Movie.objects.all()
    return render(request, 'index.html', {' movies': movies})

Here is what results on my web browser:

enter image description here

If someone knows why this is not working, any help would be awesome!

Will Goff
  • 3
  • 2

2 Answers2

0

You seem to have a space where you are passing the context:

return render(request, 'index.html', {' movies': movies})

You need to replace ' movies' with 'movies', otherwise the variable will not be available with the correct name while rendering the template.

le.chris
  • 133
  • 1
  • 7
0

As the other user @le.chris mentioned, you seem to have a space where you are passing the context. This would be the right context : return render(request, 'index.html', {' movies': movies}). However, in your views file, I highly suggest having Class-based views, start by importing the ListView in this case and create a post_list.html or specify a template_name and since you are using movies as your context object, you also need to specify that in the context_object_name attribute. Maybe like this :

class MovieListView(ListView):
    model = Movie
    template_name = 'appname/index.html' #appname is the name of your app 
    context_object_name = 'movies'
    ordering = # optional 
    paginate_by = 3

in your urls.py file of the app :

path('', MovieListView.as_view(), name='movie-index') #adjust the name as you please

Roast Biter
  • 651
  • 1
  • 6
  • 22