Django autocomplete_light and admin interface integration

I just wanted to enable autocomplete in my admin interface. It took almost 3 hours to understand whats happening and to make it work, because for integrating in admin interface, the docs is not very clear.

You need to read the docs first

http://django-autocomplete-light.readthedocs.org/en/latest/quick.html

And the read this

Scenario:

class A(models.Model):
    fieldA1 = models.CharField()
    fieldA2 = models.CharField()

class B(models.Model):
    fieldB1 = models.ForeignKey(A)
    fieldB2 = models.CharField()

For having autocomplete in admin interface for model B to the fieldB1, we need

  1. API for model A should be exposed
#Create a file autocomplete_light_registry.py in the base folder of the project 
#By registering the modelA, the /autocomplete/AAutocomplete/?q=aa API will be available 
#API will search on fieldA1 to give the result
autocomplete_light.register(A,search_fields=['fieldA1',], )
  1. Admin interface should know that fieldB1 should use that exposed API
#admin.py
class BAdmin(admin.ModelAdmin):
   form = autocomplete_light.modelform_factory(B)
admin.site.register(B, BAdmin)
This entry was posted in Django, python. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *