Generic views exist to make our lifes easier, but the time spent on understanding how these stuff work makes them harder actually. Maybe it's me but I've trying to figure how to fix this for a l开发者_运维问答ong time that I could write the view myself easily and move on but I insisted on learning it.
I want a custom DetailView class to be shown, the code throws:
'Sculpture' object has no attribute 'filter'
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
from sculptures.models import Sculpture
class SculptureListView(ListView):
"""docstring for SculptureListView"""
def get_queryset(self):
return Sculpture.objects.all()
class SculptureDetailView(DetailView):
"""docstring for SculptureDetailView"""
def get_queryset(self):
sculpture = get_object_or_404(Sculpture, slug=self.kwargs['slug'])
return sculpture
I know it requires one line fix -- at most but couldn't figure out.
And ideas?
get_queryset
, as the name implies, should return a Queryset, not a single object.
to return a single object, use get_object
class SculptureDetailView(DetailView):
"""docstring for SculptureDetailView"""
def get_object(self):
sculpture = get_object_or_404(Sculpture, slug=self.kwargs['slug'])
return sculpture
精彩评论