Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a Django detail view with a generic class based view

I know this is really simple, but I'm missing something. And because I can't ever remember this, I'm hoping this can document a solution here.

All I want to do is pass a PK for the object in the URL and get the detail view back.

Url:

    url(regex=r'^(?P<pk>\d+)/$',
    view=AdventureDetail.as_view(),
    name='adventure_detail',
),

View:

class AdventureDetail(DetailView):
""" Get a time entry detail view """

    template_name = "adventure/AdventureDetail.html"

    def get_object(self):
        return get_object_or_404(Page)

But I'm getting a "multiple objects returned error"

MultipleObjectsReturned at /1/ get() returned more than one Page -- it returned 5! Lookup parameters were {}

This feels really silly. It should "just work" but I'm missing something obvious.

Thanks for the help.

like image 422
Dave Merwin Avatar asked Jan 13 '23 12:01

Dave Merwin


2 Answers

In DetailView it is more simpler: you can just specify the model:

class AdventureDetail(DetailView):
""" Get a time entry detail view """

    model = Page
    template_name = "adventure/AdventureDetail.html"

And that's all. DetailView will do the rest of work.

Another way is to specify queryset:

class AdventureDetail(DetailView):
""" Get a time entry detail view """

    queryset = Page.objects.all()
    template_name = "adventure/AdventureDetail.html"

This will have the same result.

And the last way is to override the get_object method.

Look here for details

like image 136
stalk Avatar answered Jan 23 '23 00:01

stalk


You're not passing any other parameters to get_object_or_404, other than the Page class. So now you're basically querying for all pages. So you'd need to do:

return get_object_or_404(Page, pk=self.kwargs.get('pk', None))

Also, why are you overriding get_object? The DetailView already contains this functionality so all you need to do is have a URL with pk in it.

like image 43
Simeon Visser Avatar answered Jan 23 '23 02:01

Simeon Visser