How to display a query on DetailView in Django?

308 Views Asked by At

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?

3

There are 3 best solutions below

0
CatCoder On BEST ANSWER

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 
1
Pourya Mansouri On

remove first from queryset:

class CustomDetailView(DetailView):
    model = Flashcard 
    template_name = "flashcards.html"
    queryset = Flashcard.objects.all()
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'
    enter code here

and add id to url:

path('/<int:pk>/', CustomDetailView.as_view(), name='flashcards'),
0
Pavel Vergeev On

You need your pk or slug in

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

See an example from the docs:

urlpatterns = [
    path('<slug:slug>/', ArticleDetailView.as_view(), name='article-detail'),
]

This is because DetailView is inheriting from SingleObjectMixin, and it fetches objects that way. If you want, jump to definition of this class in your IDE to see its implementation of get_queryset and get_object.

How you call your pk or slug really depends on your model, the Flashcard. If your primary_key field is an Integer, I think you'll be fine writing

path('<int:pk>', CustomDetailView.as_view(), name='flashcards'),

edit: as Pourya Mansouri wrote, you do need to remove queryset attribute in your case too

The slug you can customize with slug_field and similar attributes.

You can define a completely custom object fetching behavior by overriding get_object or get_queryset. Here's a random examples of doing that I found on the internet: