Django: DetailView implementing a get_queryset()

Papouche Guinslyzinho picture Papouche Guinslyzinho · Jul 25, 2017 · Viewed 8.2k times · Source

I'm getting this following error:

ImproperlyConfigured at /elearning/7447932a-6044-498a-b902-97cbdd0a4001/
DetailView is missing a QuerySet. Define DetailView.model, DetailView.queryset, or override DetailView.get_queryset().

Following the Django documentation on DetailView the get_query is not mandatory unless that I want to override it.

view.py

class CourseDetailView(DetailView):

    model = Course
    template_name='elearning/detail.html'

    def get_object(self):
        course = get_object_or_404(Course, pk=self.kwargs['pk'])
        return self.model.objects.filter(pk=pk)

    def get_context_data(self, **kwargs):
        context = super(CourseDetailView, self).get_context_data(**kwargs)
        context['now'] = timezone.now()
        return context

urls.py

url(r'^(?P<pk>[0-9a-z-]+)/$', views.DetailView.as_view(), name='course-detail'),

listview template

 <a href="{% url 'elearning:course-detail' article.course_id %}">{{ article.title }}</a>

models.py

class Course(models.Model):
    course_id = models.UUIDField(default=uuid.uuid4, editable=False)
    ...

I would like to know why should I implement a get_queryset()?

I still get the same error when I add a get_queryset()

def get_queryset(self):
    qs = super(CourseDetailView, self).get_queryset()
    return qs.filter(pk=self.kwargs['pk'])

Answer

Exprator picture Exprator · Jul 25, 2017

your view is named CourseDetailView but you are using DetailView in url

url(r'^(?P<pk>[0-9a-z-]+)/$', views.DetailView.as_view(), name='course-detail'),

so the url will be

url(r'^(?P<pk>[0-9a-z-]+)/$', views.CourseDetailView.as_view(), name='course-detail'),