django-viewsdjango-class-based-viewsdjango-contextdjango-request

I'm trying to incorporate multiple models into a single django view; how can I access the context **kwargs


I've tried this:

class MyClass(LoginRequiredMixin, UpdateView, ListView):
    model = models.my_model
    fields = ['first_model_field', 'second_model_field']
    template_name = 'app/template_name.html'
    extra_context = {'second_model': models.second_model.objects.get(pk=self.kwargs['pk']),#didn't work
'third_model':models.third_model.objects.get(pk='pk'),#didn't work
'fourth_model':models.fourth_model.objects.get(foreign_key_id = 'unique_kwarg')}#didn't work.

I also have url's that contain both the /<int:pk>/ kwarg and the /<int:unique_kwarg>/ kwarg.

I am having trouble figuring out how to reference the url **kwarg object.


Solution

  •     def form_valid(self, form):
            form_template_id = self.kwargs.get(self.pk_url_kwarg)
            form.instance.model_id = model.objects.get(pk=form_template_id)
            return super().form_valid(form)
    

    and

        def get_context_data(self, **kwargs):
            """Insert the form into the context dict."""
    
            if 'unique_kwarg' not in kwargs:
                kwargs['unique_kwarg'] = (self.kwargs.get(self.unique_kwarg))
                kwargs['model_id'] = (model.objects.get(id=self.kwargs.get(self.unique_kwarg)))
    
    
            return super().get_context_data(**kwargs)