How do I make the page list all posts that that share the same category id? I have the category titles as a separate "foreign key" model. My goal is to be able to type in my URL so that I have the category id at the end and it shows me all the posts that have the specific category id.
"""models.py"""
class Category(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField()
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('post-category', kwargs={'pk': self.pk})
class HelpPage(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(default="test")
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.CharField(max_length=100)
category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
"""views.py"""
class CategoryDetailView(DetailView):
model = Category
context_object_name = 'category'
template_name = 'blog/categories.html'
"""urls.py"""
from .views import (
CategoryDetailView,)
urlpatterns = [
path('category/<int:pk>', CategoryDetailView.as_view(), name='post-category'),]
"""categories.html"""
{% extends "blog/base.html" %}
{% block content %}
Category name: {{ category.name }}
{% for post in category.post_set.all %}
post: {{ post.title }}
{% endfor %}
{% endblock content %}
