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
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,)
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With