Filter project in a detail view

Viewed 46

I have a ProjectLogo model that has a list view, a detail view etc. Then I have a ProjectFile model, that inherits the ProjectLogo with a ForeignKey. The ProjectFile also has a list view, detail view etc.

class ProjectFile(models.Model):
project = models.ForeignKey(ProjectLogo, on_delete=models.CASCADE, null=True)

On the DetailView of the ProjectFile I added some buttons that takes me to the previous and next files.

class ProjectFilesDetailView(LoginRequiredMixin, DetailView):
template_name = 'projects/files/detail_project_logo_file.html'
model = ProjectFile

def get_context_data(self, **kwargs):
    data = super(ProjectFilesDetailView, self).get_context_data(**kwargs)
    comments = ProjectFileComment.objects.filter(project_file=self.kwargs.get('pk'))
    data['comments'] = comments

    logo_ids = list(ProjectFile.objects.all().values_list('pk', flat=True))
    data['previous_logo_id'] = logo_ids[logo_ids.index(self.object.id) - 1]
    try:
        data['next_logo_id'] = logo_ids[logo_ids.index(self.object.id) + 1]
    except IndexError:
        data['next_logo_id'] = logo_ids[0]

    return data

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>

The issue is that if I have 2 projects for example, at a point the next file will take me to the other project. I need a query to filter by the current project.

Thank you for your help.

1 Answers

I found the solution:

file_ids = list(ProjectFile.objects.filter(project=self.kwargs.get('project_id')).values_list('pk', flat=True))

And I had to add the project_id in the url also.

Related