Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Class-based Views Customizing Class-based Views Override get_queryset

Danilo Livassan
Danilo Livassan
2,199 Points

Error in search Article

I dont understand the error in that code. In my personal computer works fine.

articles/views.py
from django.views import generic

from . import models


class ArticleList(generic.ListView):
    model = models.Article


class ArticleDetail(generic.DetailView):
    model = models.Article


class ArticleCreate(generic.CreateView):
    fields = ('title', 'body', 'author', 'published')
    model = models.Article


class ArticleUpdate(generic.UpdateView):
    fields = ('title', 'body', 'author', 'published')
    model = models.Article


class ArticleDelete(generic.DeleteView):
    model = models.Article


class ArticleSearch(generic.ListView):
    model = models.Article

    def get_queryset(self, request):
        try:
            term = self.request.GET['term']
        except:
            term = ''
        if not term or term == '':
            return Article.objects.none()
        return Departamento.objects.all().filter(body__icontains=term)

1 Answer

Josh Keenan
Josh Keenan
19,652 Points

You have gone about it slightly wrong.

    def get_queryset(self):
        if not self.kwargs['term']:
            return self.model.objects.none()
        else:
            return self.model.objects.filter(body__icontains=self.kwargs['term'])

Firstly, you don't need to take a request in the method, the class will handle that itself, your method should operate within the class.

Secondly, you are referencing tables you have locally that aren't relevant to the challenge, so whilst it passes on your computer, you have written code that isn't actually entirely for the challenge.

return Departamento.objects.all().filter(body__icontains=term)

You also miss the referencing to models.Article and feature just the latter, which treehouse won't recognise.

I personally write all challenge solutions within the editor for them, due to the fact treehouse and my local set up will be different entirely, I believe treehouse runs django 1.8/9 and the current version I am using is 3.0. There will be imports that are vastly different, and it is assessing for different things and not just necessarily the output always. Feel free to ask any questions and good luck!