[Fixed]-Django 1.10 super-easy filters

1๐Ÿ‘

โœ…

Iโ€™m giving you a minimum example, just so you read some docs in case you have some errors.

First, put your status choices into settings file, so that, just in case, you could use anywhere else.

STATUS_CHOICES = (
    ('A','Active'),
    ('U','Unactive')
)

Then you need to create a filter set, put it into models.py for now:

from django.conf import settings
import django_filters

class SearchFilter(django_filters.FilterSet):
    status = django_filters.ChoiceFilter(choices=settings.STATUS_CHOICES)

    class Meta:
        model = Contact

Then in your view:

def index(request):
    queryset_list = Contact.objects.all()
    query = request.GET.get('q', '')

    if query:
        queryset_list = queryset_list.filter(
            Q(name__icontains=query) | Q(phone__icontains=query) |
            Q(url__icontains=query) | Q(email__icontains=query)
        )

    filtered = SearchFilter(request.GET, queryset=queryset_list)
    context = {
        'filtered': filtered,
    }

    return render(request, 'index.html', context)

And finally in the template put this:

...
{{ filtered.form.status }}
...
๐Ÿ‘คAndrey Shipilov

Leave a comment