Reputation: 535
In a Django 3.0 app, I have a Donor Model with a foreign key to the donor's congressional district:
# models.py
class Donor(models.Model):
"""A class to represent an individual donor"""
name = models.CharField(
help_text = "Donor's name"
)
district = models.ForeignKey(
District,
help_text = "Donor's congressional district"
)
class District(models.Model):
"""A class to represent a U.S. congressional district"""
dist_name = models.CharField(
help_text = "District name"
)
In the Admin Add page for Donor, there's a drop-down selection menu for District. The problem is that there are 435 congressional districts in the U.S. That's an awful lot to scroll through each time I add a Donor, so I'd like to add a search box.
Django has the ability to define search fields. I tried to do so:
# admin.py
@admin.register(Donor)
class DonorAdmin(admin.ModelAdmin):
search_fields = ['district']
This did not affect the Donor Add page. 'District' still shows up as an enormous drop-down, and there are no search features anywhere on the page.
The search_fields
documentation says specifically
Set search_fields to enable a search box on the admin change list page.
Emphasis mine: search_fields
seems to apply to only the Change List page, not the Add page. I assume this is why my attempt didn't work.
Is it possible to add a search box to a Django Admin Add page?
Upvotes: 2
Views: 694
Reputation: 59
Yes, you can add a search box to Django admin pages.
Add this to your admin class:
search_fields = ['name', 'author',.......] #add the fields you want to search
And the search box it will appear
Upvotes: 1