Search code examples
djangodetailview

How to display a query on DetailView in Django?


I want my "CustomDetailView" to display a query(a single "flashcard"). I was able to it by using ListView

CustomListView(ListView):
    model = Flashcard
    template_name = 'flashcards.html
    queryset = Flashcard.objects.all()[:1]

But for DetaiView I'm getting this error Generic detail view CustomDetailView must be called with either an object pk or a slug in the URLconf.

class CustomDetailView(DetailView):
    model = Flashcard 
    template_name = "flashcards.html"
    queryset = Flashcard.objects.all().first()

urls.py

path('', CustomDetailView.as_view(), name='flashcards'),

How to fix this?


Solution

  • Maybe should have better communicated. Sorry for my English. I wanted to return a random query when I clicked on a link a show it on detailView. I was able to it by this. Don't think it's efficient. If anyone has any idea share it.

    def get_object(self):
        queryset = Flashcard.objects.order_by('?').first()
        return queryset