Pagination with Django Filter (Package) Django.How

Author avatar wrote on 03/06/2022

Views.py


from django.shortcuts import render
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from .models import CustomUser
from .filters import CustomUserFilter
import django_filters

def users(request):
    user_list = CustomUser.objects.all().order_by('id')
    user_filter = CustomUserFilter(request.GET, queryset=user_list)

    paginator = Paginator(user_filter.qs, 10)
    page = request.GET.get('page')
    paged_listings = paginator.get_page(page)

    context = {
        'filter': user_filter,
        'paginator_filter': paged_listings
    }

    if request.method == 'GET':
        print('Get')
        return render(request, 'accounts/users.html', context)

Filters.py


from .models import CustomUser
import django_filters


class CustomUserFilter(django_filters.FilterSet):
    email = django_filters.CharFilter(label='Email', lookup_expr='exact',)
    first_name = django_filters.CharFilter(label='First name', lookup_expr='icontains',)
    last_name = django_filters.CharFilter(label='Last name', lookup_expr='icontains',)

    class Meta:
        model = CustomUser
        fields = fields = {
        }
        

Template.html

Search

Listing

Paginator

CRUDgen Django CRUD generator