Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Filter in Django admin

I have a model as follows

class Person:
  name = models.CharField()
  city = models.CharField()
  phone = models.CharField()

I want to create a filter in the admin page, the filter should be based on phone, that is

valid phone(having 10 digits)
invalid phone

I don't want to create a validation. I just want to filter out who has a valid phone and invalid. Thanks

like image 594
potato tomato Avatar asked Dec 11 '25 17:12

potato tomato


2 Answers

Create a custom list filter class. There's an example in the docs which can be adopted to your case.

from django.contrib import admin

class ValidPhoneListFilter(admin.SimpleListFilter):
    # Human-readable title which will be displayed in the
    # right admin sidebar just above the filter options.
    title = _('valid phone')

    parameter_name = 'valid_phone'

    def lookups(self, request, model_admin):
        return (
            ('valid', _('valid phone')),
            ('invalid', _('invalid phone')),
        )

    def queryset(self, request, queryset):
        if self.value() == 'valid':
            return queryset.filter(phone__regex=r'^\d{10}$')
        if self.value() == 'invalid':
            return queryset.exclude(phone__regex=r'^\d{10}$')

Then include your list filter class in list_filter for your model admin.

class PersonAdmin(admin.ModelAdmin):
    list_filter = (ValidPhoneListFilter,)
like image 105
Alasdair Avatar answered Dec 13 '25 05:12

Alasdair


You could do something like

from django.core.validators import RegexValidator

phone_regex = RegexValidator(r'^[0-9]{10}$', 'Invalid phone number')

And in your model

phone = models.CharField(validators=[phone_regex])

This regex only checks if it is digits and that the length is 10. Modify it after your specific needs.

Hope this helps.

Good luck!

like image 21
LanfeaR Avatar answered Dec 13 '25 07:12

LanfeaR