DetailView multiple context


#1

View at bottom works but I wonder why I get error if I changed the line

context['detail'] = Company.objects.get(pk=self.object.id)
with
context['detail'] = Company.objects.get(pk=id)

Error :
int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'

Is there any other way to use object in context (detail) without pk=self.object.id ? I am confused about using multiple contexts in CBV

class CompanyDetail(DetailView):
    model = Company
    template_name = 'company/company_detail.html'

    def get_context_data(self, **kwargs):
        context = super(CompanyDetail,self).get_context_data(**kwargs)
        context['detail'] = Company.objects.get(pk=self.object.id)
        context['approved'] = Approved.objects.filter(register_num=self.object.company_register_num)
        context['unapproved'] = Unapproved.objects.filter(register_num=self.object.company_register_num)
        return context

#2

I changed my view and it worked. But still confused about filtering with self.object.

class CompanyDetail(DetailView):
    model = Company
    template_name = 'company/company_detail.html'
    context_object_name = 'detail'


    def get_context_data(self, **kwargs):
        context = super(CompanyDetail,self).get_context_data(**kwargs)
        context['approved'] = Approved.objects.filter(register_num=self.object.company_register_num)
        context['unapproved'] = Unapproved.objects.filter(register_num=self.object.company_register_num)
        return context

(Vitor Freitas) #3

You got an error when you tried to filter using the id because it wasn’t defined anywhere. If you wanted to filter using the id that comes in the URL, and passed to the view as a keyword argument, you should do something like that:

class CompanyDetail(DetailView):
    model = Company
    template_name = 'company/company_detail.html'

    def get_context_data(self, **kwargs):
        context = super(CompanyDetail,self).get_context_data(**kwargs)
        context['detail'] = Company.objects.get(pk=self.kwargs.get('id'))
        # ...
        return context

About the object, it is processed by the generic class-based view DetailView. You can look at the DetailView get method when Django set the self.object to the corresponding model instance

Since this is a DetailView for the Company model, you don’t need to set the context['detail'] as the Company instance. The Company instance will be available at context['object'].

If you want to change the object to something else, (like detail) you can do it like that:

class CompanyDetail(DetailView):
    model = Company
    template_name = 'company/company_detail.html'
    context_object_name = 'detail'

    # ...