Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django admin site foreign key from dropdown to search_field

Tags:

python

django

Im a bit stuck at why a foreign key drop-down field in admin site is not changing to a search field. I read the documentation that states:

These fields should be some kind of text field, such as CharField or TextField. You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API “follow” notation:

search_fields = ['foreign_key__related_fieldname']

I have two models:

class Company(models.Model):
    company = models.CharField(max_length=100)

class User(AbstractUser):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)

When I want to create a user manually via admin site I get a drop-down list of possible companies as foreign keys enter image description here

I though that this solution should change the drop-down to a search field but it isnt. What am I doing wrong here? How to change this foreign key field to a search field?

admin.py from django.contrib import admin from .models import Company, User

class MyAdmin(admin.ModelAdmin):
    search_fields = ['company__company']


admin.site.register(Company)
admin.site.register(User, MyAdmin)
like image 690
d1spstack Avatar asked Nov 18 '25 04:11

d1spstack


1 Answers

You should use autocomplete_fields for this. Configure search_fields on the admin that you want to search and add the foreign key to that admin/model to autocomplete_fields

class CompanyAdmin(admin.ModelAdmin):
    search_fields = ['company']


class MyAdmin(admin.ModelAdmin):
    autocomplete_fields = ['company']


admin.site.register(Company, CompanyAdmin)
admin.site.register(User, MyAdmin)
like image 166
Iain Shelvington Avatar answered Nov 20 '25 18:11

Iain Shelvington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!