Django:实现ProjectFile详情页同项目内文件上下切换
解决同项目内ProjectFile上下切换问题
问题说明
当前ProjectFile详情页的上下切换按钮会跳转到其他项目的文件,原因是查询所有ProjectFile的id列表时,没有过滤当前文件所属的项目。
修改后的视图代码
class ProjectFilesDetailView(LoginRequiredMixin, DetailView): template_name = 'projects/files/detail_project_logo_file.html' model = ProjectFile def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) comments = ProjectFileComment.objects.filter(project_file=self.kwargs.get('pk')) data['comments'] = comments # 仅获取当前文件所属项目的文件,按id排序保证顺序稳定 project_files = ProjectFile.objects.filter(project=self.object.project).order_by('id') logo_ids = list(project_files.values_list('pk', flat=True)) current_index = logo_ids.index(self.object.id) # 处理上一个文件:当前是第一个时,跳转到最后一个 data['previous_logo_id'] = logo_ids[current_index - 1] if current_index > 0 else logo_ids[-1] # 处理下一个文件:当前是最后一个时,跳转到第一个 data['next_logo_id'] = logo_ids[current_index + 1] if current_index < len(logo_ids)-1 else logo_ids[0] return data
关键修改点
- 项目过滤:用
filter(project=self.object.project)替代all(),只查询当前文件所属项目下的所有文件,彻底避免跨项目跳转。 - 稳定排序:添加
order_by('id')(也可以换成created_at等时间字段),保证文件的顺序固定,不会因数据库默认排序导致切换顺序混乱。 - 边界逻辑优化:用条件判断替代try-except,更清晰处理第一个/最后一个文件的循环切换场景。
HTML代码无需修改
保持原有的跳转链接代码即可:
<a class="btn btn-outline-primary float-end" href="{% url 'detail-project-logo-files' previous_logo_id %}" role="button" data-bs-toggle="tooltip" title="Previous file!">❮</a> <a class="btn btn-outline-primary float-end" href="{% url 'files-project-logo' projectfile.project_id %}" role="button">View all</a> <a class="btn btn-outline-primary float-end" href="{% url 'detail-project-logo-files' next_logo_id %}" role="button" data-bs-toggle="tooltip" title="Next file!">❯</a>
内容的提问来源于stack exchange,提问作者ciprian_mihu
相关产品推荐
相关产品推荐

