Django ListView not showing up in frontend

551 Views Asked by At

I am trying to create a gym workout basic app in Django, and wish to have my workouts displayed as a list on my home page, using Django's built-in list view. For some reason, my home page template is rendering, with the proper headers and nav bar, but my list is not showing. Here is my code:

Models.py

from django.db import models

STATUS = (
    (0,"Draft"),
    (1,"Publish")
)

class Workout(models.Model):
    workout_number = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    created_on = models.DateTimeField(auto_now_add=True)
    content = models.TextField()
    description = models.TextField(blank=True, default='')
    time_cap = models.TimeField(auto_now=False, auto_now_add=False, blank=True) 
    rounds = models.IntegerField(blank=True, default='') 
    weight = models.FloatField(blank=True, default='')
    status = models.IntegerField(choices=STATUS, default=0) 

    class Meta:
        ordering = ['-created_on']

    def __str__(self):
        return self.name

Views.py

from django.shortcuts import render
from django.views import generic 
from .models import Workout

class WorkoutList(generic.ListView):
    model = Workout
    template_name = 'home.html'
    context_object_name = 'workout'
    queryset = Workout.objects.filter(status=1).order_by('-created_on')

Template home.html (part of)

<div class="container">
    <div class="row">
        <div class="col-md-8 mt-3 left">
            {% for workout in workout_list %}
            <div class="card mb-4">
                <div class="card-body">
                    <h2 class="card-title">{{ workout.name }}</h2>
                    <p class="card-text text-muted h6">{{ workout.created_on}} </p>
                    <p class="card-text">{{workout.content|slice:":200" }}</p>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>

Workout/Urls.py

from django.urls import path
from . import views

app_name='workout'

urlpatterns = [
    path('', views.WorkoutList.as_view(), name='home'),
]

1

There are 1 best solutions below

5
On

Since the context_object_name is 'workout', this means that the list of objects is passed as workout, but you iterate over {% for workout in workout_list %}. You should change this to:

from django.shortcuts import render
from django.views import generic 
from .models import Workout

class WorkoutList(generic.ListView):
    model = Workout
    template_name = 'home.html'
    context_object_name = 'workout_list'
    queryset = Workout.objects.filter(status=1).order_by('-created_on')