Using search and pagination field with Function Based View in Django

Asked

Viewed 744 times

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>

So I wanted to create a search ground.

I tried to:

# 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 lost my train of thought, because notice I have two request.GET.get. And the filter would be done later, in persons = PersonProfile.objects.all().filter(...)

Can someone help me figure out how to fix this?

second option: use CBV. I would know how to do it, but then I can’t authenticate using the LoginRequiredMixin adapted to superuser_required.

1 answer

1


@Regis

I believe that the filter has priority over paging, because first you should know what is the result of your filter and then page 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.