Using search and pagination field with Function Based View in Django

0

I have the following code:

#decorators.py
from django.contrib.auth.decorators import user_passes_test

def superuser_required(func):
    return user_passes_test(
        lambda u: u.is_authenticated() and u.is_superuser)(func)


# views.py
@superuser_required
def dashboard_persons(request):
    persons = PersonProfile.objects.all()

    paginator = Paginator(persons, ENTRIES_PER_PAGE)
    page = request.GET.get('page', 1)
    persons = paginator.page(page)

    return render(request, 'dashboard/dashboard_persons.html', {'persons': persons })

# dashboard_persons.html
<form>
  <div class="row">
    <div class="six columns">
      <input class="u-full-width" type="text" placeholder="Localizar..." name="search_box">
    </div>
  </div>
</form>

I wanted to create a search field .

I've tried:

# views.py
@superuser_required
def dashboard_persons(request):
    persons = PersonProfile.objects.all()

    paginator = Paginator(persons, ENTRIES_PER_PAGE)
    page = request.GET.get('page', 1)
    persons = paginator.page(page)

    q = request.GET.get('search_box')
    if q:
        persons = persons.filter(full_name__icontains=q)

    return render(request, 'dashboard/dashboard_persons.html', {'persons': persons })

But I've lost my reasoning, because you notice that I have two request.GET.get. And the filter would be done later, in persons = PersonProfile.objects.all().filter(...)

Can anyone help me with how to solve this?

2nd option: use CBV. I would know how to do this, but I do not know how to do this using LoginRequiredMixin adapted to superuser_required .

    
asked by anonymous 30.06.2016 / 05:36

1 answer

1

@Regis

I believe the filter takes precedence over paging because you must first know what the result of your filter is and then paginate the results returned by it.

Then the code would look like this:

@superuser_required
def dashboard_persons(request):
    persons = PersonProfile.objects.all()

    filter = request.GET.get('search_box', None)
    if filter:
        persons = persons.filter(full_name__icontains=filter)

    paginator = Paginator(persons, ENTRIES_PER_PAGE)
    page = request.GET.get('page', 1)
    persons = paginator.page(page)

    return render(request, 'dashboard/dashboard_persons.html', {'persons': persons, 'filter': filter })

I'm returning the filter in context because I believe you want to keep it in the search field.

    
30.06.2016 / 11:08