C
C
constlapkin2020-02-03 14:49:16
Python
constlapkin, 2020-02-03 14:49:16

How to pass object id from context to get_context_data()?

I have two models:

class Project(BaseModel):
    slug = models.SlugField(verbose_name='URL', unique=True, blank=False)
    category = models.ManyToManyField(Category, verbose_name='Category')
    title = models.CharField(max_length=200, verbose_name='Title', blank=False)
    publication = models.BooleanField(verbose_name='Publication', default=True)

and
class Screenshot(BaseModel):
    image = models.ImageField(upload_to='uploads/projects/%Y/%m/', verbose_name='Image', blank=False)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)

I'm using a project view but don't know how to link images to a project by its id.
I do something like this:
class ProjectDetailView(DetailView):
    model = Project
    template_name = 'portfolio/project_detail.html'
    context_object_name = 'project'
    queryset = Project.objects.filter(publication=True)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['screenshots'] = Screenshot.objects.filter(project=???) # id from Project object
        return context


That is, through get_context_data () I add image model objects to the context, but how to filter them by project id?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2020-02-03
@constlapkin

Like so:

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['screenshots'] = Screenshot.objects.filter(project=self.object) # id from Project object
        return context

But in general, you already have it passed in the properties of the project instance as a screenshot_set. Accordingly, they can be taken from there, and not produce an entity

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question