Mastering Development

Django_Filters and queryset

Hi guys I’m building a simple django website where the user can look for long play. The problem right now is that I can’t figure out why the filter, built with the django_filters library, doesn’t work.

If you type “Queen” in the search bar in the home you are redirected to the searches.html where are listed all the LPs by Queen (just 4). On the left there’s a filter. If you type “kind” in the form and submit then you should just see the album “Kind of Magic”. This doesn’t work. And I think the problem is the queryset “sp”:

class searchesView(TemplateView):
    template_name = "search/searches.html"

    def post(self, request, *args, **kwargs):
        print('FORM POSTED WITH {}'.format(request.POST['srh']))
        srch = request.POST.get('srh')

        if srch:

            sp = Info.objects.filter(Q(band__icontains=srch)) | Info.objects.filter(Q(disco__icontains=srch))
            myFilter = InfoFilter(request.GET, queryset=sp)
            sp = myFilter.qs

            paginator = Paginator(sp, 10)
            page_number = request.GET.get('page')
            page_obj = paginator.get_page(page_number)

            return render(self.request, 'search/searches.html', {'sp':sp, 'myFilter':myFilter,
                                                                       'page_obj': page_obj
            return render(self.request, 'search/searches.html')

I think the problem is the queryset because then I tried to build a result.html page where I listed all the LPs in the database and applied the same filter above and here it works perfectly:

def result(request):
    result = Info.objects.all()
    myFilter = InfoFilter(request.GET, queryset=result)
    result = myFilter.qs
    return render (request, 'search/result.html', {'result':result, 'myFilter':myFilter})

The difference is that in the first case I’ve got a TemplateView with a certain queryset, and in the second case I’ve got a simple function with a different queryset. Someone know what the problem could be? I uploaded to code on repl if you want to try out the website:

Thanks a lot!

Leave a Reply

Your email address will not be published. Required fields are marked *