django ListView

context_object_name = 'posts'. The template default name is ListView 'object_list'

from .models import Post,Category
from django.views.generic.list import ListView
from django.shortcuts import get_object_or_404

class PostCategory(ListView):
    model = Post
    template_name = 'cat.html'
    context_object_name = 'posts'
    def get_queryset(self):
        self.category = get_object_or_404(Category, pk=self.kwargs['pk'])
        return Post.objects.filter(category=self.category)

    def get_context_data(self, **kwargs):
        context = super(PostCategory, self).get_context_data(**kwargs)
        context['category'] = self.category
        return context
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当你需要展示一个对象列表时,可以使用Django内置的ListView视图。以下是一个简单的示例: 1. 首先,在你的Django项目中的views.py文件中导入ListView和你的模型类: ```python from django.views.generic import ListView from .models import YourModel ``` 2. 创建一个继承自ListView的视图类,并指定要使用的模型和模板: ```python class YourListView(ListView): model = YourModel template_name = 'your_template.html' ``` 在这个示例中,我们创建了一个名为YourListView的视图类,使用YourModel作为数据源,并使用名为your_template.html的模板进行渲染。 3. 在你的urls.py文件中添加一个URL模式来映射到YourListView: ```python from .views import YourListView urlpatterns = [ # 其他URL模式... path('your-list/', YourListView.as_view(), name='your_list'), ] ``` 在这个示例中,我们创建了一个名为"your_list"的URL模式,当用户访问/your-list/时,将调用YourListView来展示对象列表。 4. 创建一个名为"your_template.html"的模板文件,放在你的Django项目中的templates目录下: ```html <!DOCTYPE html> <html> <head> <title>Your Object List</title> </head> <body> <h1>Your Object List</h1> <ul> {% for object in object_list %} <li>{{ object }}</li> {% empty %} <li>No objects found.</li> {% endfor %} </ul> </body> </html> ``` 在这个示例中,我们简单地在模板中添加了一个标题和一个无序列表,通过使用模板标签{% for %}和{{ object }}来遍历并显示对象列表。如果列表为空,将显示"No objects found."。 现在,当用户访问/your-list/时,Django将使用YourListView来获取YourModel的对象列表,并使用your_template.html进行渲染,并将结果返回给用户。 这只是一个简单的示例,你可以根据自己的需求来扩展和定制ListView。可以在Django官方文档中找到更多关于ListView的使用说明和示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值