0

I'm using Django==1.11. As I understand from class based views, in this case ListView, you can access url params in get_queryset with self.kwargs, as answered here and here. And I have no problem when I use get_context_data and self.kwargs.

But I can't get it to work in get_queryset. ¿What I'm doing wrong or missing? I've been trying so many alternatives but I can't get the right one.

My code:

urls

urlpatterns = [
    url(r'^escuelas/(?P<level>(inicial|primario|secundario))/$', SchoolListView.as_view(), name='school-by-level-index'),
    #...

view

class SchoolListView(ListView):
    model = School
    template_name = 'edu/adminlte/school_index.html'

    def get_queryset(self):
        queryset = super(SchoolListView, self).get_queryset()
"""
Here below self.kwargs['level'] does not return anything as I would expect
"""
        level = self.kwargs['level']

        if level is 'inicial':
            queryset = School.objects.filter(level='I')
            return queryset
        return queryset 

Thanks.

schrodingerscatcuriosity
  • 1,780
  • 1
  • 16
  • 31
  • move the `level = self.kwargs['level']` line before the `super()` call. – Burhan Khalid Jun 21 '18 at 23:12
  • @BurhanKhalid nothing happened – schrodingerscatcuriosity Jun 21 '18 at 23:29
  • Is the queryset returning as expected outside of the if statement? Are you sure 'level' is in the kwargs? – leelum1 Jun 21 '18 at 23:44
  • @leelum1 Yes the queryset works fine. If I put `level='initial'` it works, no problem with the query itself. The kwargs, as I understand should work from de url pattern, as I said with `get_context_data`, applying the same logic, it works. – schrodingerscatcuriosity Jun 21 '18 at 23:49
  • Oh I understand now. How are you calling the ListView? – leelum1 Jun 22 '18 at 00:11
  • @leelum1 What do you mean by calling the ListView? It is in the urls pattern `SchoolListView.as_view()`. I mean, and maybe should clarify, that theres no problem either with the template display of the query (without filter). The view just don't get the parameter with `self.kwargs['level']`, so I can't filter the query from it. – schrodingerscatcuriosity Jun 22 '18 at 00:18

1 Answers1

0

I knew it was something simple:

double equals vs is in python

My code was:

    if level is 'inicial':

But it had to be

    if level == 'inicial':
schrodingerscatcuriosity
  • 1,780
  • 1
  • 16
  • 31