Search code examples
pythondjangodjongo

Unable to pass model to context


I'm trying to pass a single model, and a list of models with the same "document_title" to my ModelDetailView template. The code for the views.py section is

class DocumentDetailView(generic.DetailView):

    model = Document

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["doc_list"] = Document.objects.filter(model.document_title).order_by('revision_number')
        return context

I have tried passing the model into the get_context_data method, but that only produces other errors. I'm not sure if I'm going about this the correct way, but any ideas would greatly help.

EDIT: I've fixed the indentation of the code snippet.


Solution

  • As others have stated, your filter on line 5 is incorrect. Also, depending on your version of Django, the DetailView.get_context_data passes the detail item in question as object, which you should use in your filter.

    Finally, your indentation seems to be off but that could just be bad copy/paste.

    class DocumentDetailView(generic.DetailView):
    
      model = Document
    
      def get_context_data(self, object, **kwargs):
        context = super().get_context_data(object, **kwargs)
        context["doc_list"] = Document.objects.filter(document_title=object.document_title).order_by('revision_number')
        return context