在Django中显示类别列表中的帖子列表可以通过以下步骤实现:
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.title
from django.shortcuts import render
from .models import Category, Post
def category_list(request):
categories = Category.objects.all()
posts = Post.objects.all()
context = {
'categories': categories,
'posts': posts
}
return render(request, 'category_list.html', context)
{% for category in categories %}
<h2>{{ category.name }}</h2>
<ul>
{% for post in posts %}
{% if post.category == category %}
<li>{{ post.title }}</li>
{% endif %}
{% endfor %}
</ul>
{% endfor %}
from django.urls import path
from .views import category_list
urlpatterns = [
path('categories/', category_list, name='category_list'),
]
完成以上步骤后,当访问/categories/路径时,将会显示类别列表中的帖子列表。每个类别下的帖子将按照标题进行展示。
注意:以上代码仅为示例,实际应用中可能需要根据具体需求进行适当的修改和优化。
推荐的腾讯云相关产品:腾讯云服务器(CVM)、腾讯云数据库(TencentDB)、腾讯云对象存储(COS)等。您可以访问腾讯云官网了解更多产品信息和详细介绍:https://cloud.tencent.com/
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云