本文解决 Django ListView 中因错误覆盖 context_object_name 导致上下文为空的问题,详解如何安全地按登录用户过滤照片、保留分页与默认行为,并提供可复用的代码实践与关键注意事项。 本文解决 django listview 中因错误覆盖 `context_object_name` 导致上下文为空的问题,详解如何安全地按登录用户过滤照片、保留分页与默认行为,并提供可复用的代码实践与关键注意事项。在 Django 的 ListView 中,若需让每个登录用户仅查看自己上传的照片,绝不能直接覆写 context'photos' 为新的 QuerySet------这会破坏 ListView 内置的分页逻辑(如 page_obj、is_paginated)、对象计数及默认上下文结构,导致模板中 photos 变为空或分页失效。根本问题在于:你调用了 super().get_context_data(),但随后用 context'photos' = ... 完全替换了由 ListView 自动注入的、已包含分页信息的 QuerySet。正确做法是在 get_queryset() 中完成数据过滤,让 ListView 基于过滤后的 QuerySet 自动构建完整上下文。? 正确实现如下:# views.pyfrom django.contrib.auth.mixins import LoginRequiredMixinfrom django.views.generic import ListViewclass PhotoList(LoginRequiredMixin, ListView): model = Photo template_name = 'main/gallery.html' context_object_name = 'photos' paginate_by = 12 # 可选:启用分页 def get_queryset(self): # 始终从当前用户出发过滤 qs = Photo.objects.filter(user=self.request.user) # 按 category 参数进一步筛选(若提供) category_name = self.request.GET.get('category') if category_name: qs = qs.filter(category__name=category_name) return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # 仅添加额外上下文,不干扰 photos 主体 context'categories' = Categories.objects.all() return context? 关键说明: 橙篇 百度文库发布的一款综合性AI创作工具
相关推荐
星云穿梭12 小时前
用Python写一个带图形界面的学生管理系统——完整教程金銀銅鐵12 小时前
用 Pygame 实现 15 puzzle倔强的石头_18 小时前
《Kingbase护城河》——数据库存储空间全景探测与精细化瘦身实战黄忠18 小时前
大模型之LangGraph技术体系冬奇Lab1 天前
每日一个开源项目(第134篇):Zvec - 阿里开源的嵌入式向量数据库,向量搜索界的 SQLitehboot1 天前
AI工程师第二课 - 数据处理用户8356290780511 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置用户8356290780512 天前
用 Python 自动化 PowerPoint 演讲者备注添加ClouGence2 天前
Oracle CDC 架构优化:从主库直连到 DataGuard 备库同步黄忠2 天前
01-系统架构设计-LangGraph状态机与多源异构RAG