I've tried to create a simple app that has a list of Categories and each Category has a list of Posts.
When I delete a Category object in Django Admin it disappears in Admin but it remains rendered in the template. Here is Admin showing only two Categories
However, on the home.html it shows 3..
the base.html serving the Navbar also shows 3
I have cleared cache and hard reload. Here is my code:
Views.py
from django.shortcuts import render, get_object_or_404
from .models import Post, Category
from django.views.generic import ListView, DetailView
category_list = Category.objects.all()
def privacy(request):
return render (request, 'privacy.html', {'category_list':category_list})
def home(request):
return render(request,'home.html',{'category_list':category_list})
def categoryDetail(request, slug):
category = get_object_or_404(Category, slug=slug)
post = Post.objects.filter(category=category)
return render(request,'category_detail.html',{'category':category, 'post':post, 'category_list':category_list})
and template, home.html
{% if category_list %}
<!-- Content Row -->
<div class="row">
{% for cat in category_list %}
<div class="col-md-4 mb-5">
<div class="card h-100">
<div class="card-body">
<h2 class="card-title"><a href="{% url 'category_detail' cat.slug %}">{{ cat.name }}</a></h2>
<p class="card-text">{{ cat.summary|truncatechars:100 }}</p>
</div>
<div class="card-footer">
<a href="{% url 'category_detail' cat.slug %}" class="btn btn-primary btn-sm">More Info</a>
</div>
</div>
</div>
{% endfor %}
</div>
<!-- /.row -->
{% else %}
<h3>COMING SOON ...</h3>
{% endif %}
an similarly in base.html
<ul class="navbar-nav ml-auto">
{% for cat in category_list %}
<li class="nav-item">
<a class="nav-link" href="{% url 'category_detail' cat.slug %}">| {{cat.name}}</a>
</li>
{% endfor %}
</ul>
models.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=255)
summary = models.TextField()
slug = models.SlugField(max_length=255, unique=True)
def __str__(self):
return self.name
class Post(models.Model):
title= models.CharField(max_length=255)
category = models.ForeignKey('Category', on_delete=models.CASCADE)
def __str__(self):
return self.title
i followed a you tube video on creating these functions in the Views.py because I wanted to be able to display detail of a Category and the list of posts in it on the same page... I have a horrible feeling my error is due to defining category_list outside of a function...or worse!
Also, do I need to write a function to base.html to dynamically update the menu options?