如何在Django-CMS的Apphook中添加ListView查询集到上下文?
解决Django CMS Apphook无法获取ListView查询集的问题
针对你的情况,分两种场景给出具体解决方案:
场景1:通过Apphook挂载ListView页面,需要模板获取object_list
如果是直接通过Apphook绑定ListView来生成页面,按以下步骤排查修正:
确认cms_apps.py的Apphook配置正确关联视图路由
确保你的Apphook类正确引入了包含ListView的urlpatterns:from django.utils.translation import gettext_lazy as _ from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from .urls import urlpatterns @apphook_pool.register class ServiceApphook(CMSApp): name = _("服务列表Apphook") urls = urlpatterns确保urls.py正确映射到ServiceListView
路由文件要把根路径指向你的ListView:from django.urls import path from .views import ServiceListView urlpatterns = [ path('', ServiceListView.as_view(), name='service-list'), ]检查ServiceListView的查询集逻辑
视图要正确返回Service模型的查询集,默认model = Service会自动获取所有数据,也可以自定义查询逻辑:from django.views.generic import ListView from .models import Service class ServiceListView(ListView): model = Service template_name = 'service_list.html' # 可选:自定义查询集 def get_queryset(self): return Service.objects.filter(is_active=True).order_by('-created_at')验证CMS页面已挂载Apphook
在Django CMS后台编辑对应页面,在「高级」选项卡中选择你创建的ServiceApphook,保存后访问页面,模板里即可直接使用{{ object_list }}遍历数据。
场景2:在CMS插件中需要获取Service查询集
如果你是想在ServicePlugin对应的模板中获取数据,需要在插件类的render方法中手动添加查询集到上下文:
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from .models import ServicePluginModel, Service @plugin_pool.register_plugin class ServicePlugin(CMSPluginBase): model = ServicePluginModel name = "服务列表插件" render_template = "service_plugin.html" def render(self, context, instance, placeholder): context = super().render(context, instance, placeholder) # 将查询集添加到上下文,模板中用{{ services }}调用 context['services'] = Service.objects.all() return context
额外排查点
- 确认Service模型中存在数据,避免因空查询集误以为未传入上下文
- 检查模板文件路径是否正确,需放在应用的
templates目录下(如your_app/templates/service_list.html)
内容的提问来源于stack exchange,提问作者ytsejam
相关产品推荐
相关产品推荐

