0

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.

3 Answers3

1

You are using the filter incorrectly. What you need to do is:

context["doc_list"] = Document.objects.filter(document_title=self.object.document_title).order_by('revision_number')
Sanip
  • 1,772
  • 1
  • 14
  • 29
0

The object for the detail view is accessible as self.object.

context["doc_list"] = Document.objects.filter(document_title=self.object.document_title).order_by('revision_number')
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • It seems as if I'm still getting the same error as before. I might have something else going wrong. The error is `ImproperlyConfigured at ` and `DocumentDetailView is missing a QuerySet`. @Sanip this applies to your response as well. Thank you both. – Wilson Miller Feb 14 '19 at 15:13
  • Well that isn't related to your question. Is the indentation correct? Are `model` and `get_context_data` indented inside the class? – Daniel Roseman Feb 14 '19 at 15:15
  • Sorry about that. I figured that the issue was the query not being setup correctly. That being said the context works perfectly fine when the query isn't filtering and returns all. – Wilson Miller Feb 14 '19 at 15:20
0

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
RYou
  • 46
  • 5
  • This seemed to work! The only thing I had to change was to have context initialized as `context = super().get_context_data(**kwargs)`. I guess the version of Django I'm using doesn't support having 2 arguments there. Thank you for your help. – Wilson Miller Feb 14 '19 at 15:42