I have a need to customize autocomplete field on django admin.
So basically, I filter out serial numbers.
In some cases, users input numbers with preceding zeroes like this. 00001234
The actual search should be done for 1234.
So all I need is to get rid of preceding zeroes from user input.
How can I do this?
Any help would be appreciated
@KenWhitesell , any idea on this?
If you’re using the Django Admin autocomplete field for the search, it calls (among other things) the ModelAdmin method get_search_results. You could override that method in your ModelAdmin class to remove leading zeros from the search parameter.
My fields are
Then I’m not following what you’re referring to here.
You must define
search_fields on the related object’s
ModelAdmin because the autocomplete search uses it.
So in your data entry form, if you have an FK using the autocomplete field, it is calling the search on the target model.
That makes sense. But I am not sure when the method
get_search_results is called
It is only called on list view
I just tried it out - when I go to edit an entity using an auto complete field referencing an FK-related model, that target model’s get_search_results method gets called.
name = models.CharField(max_length=100)
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
headline = models.CharField(max_length=255)
form = BlogForm
search_fields = ['name']
def get_search_results(self, request, queryset, search_term):
print("In get search results")
results = super().get_search_results(request, queryset, search_term)
autocomplete_fields = ['blog']
This will print “In get search results” on the console every time a key is pressed in the ‘blog’ field when editing an Entry object.
Yes, you are right!
I should override that method on the target admin, not caller’s admin.