Search code examples
djangoautocompletemany-to-manydjango-grappelli

Django Grappelli Autocomplete M2M


I followed the docs down to the letter and can't get the M2M autocomplete lookup to work in Grappelli.

#models.py
#main model
class Entry(models.Model):
    title = models.CharField(max_length=60)
    content = models.TextField()
    keywords = models.ManyToManyField(Keyword, blank=True)


#model I want to be searched through while typing in the autocomplete field
class Keyword(models.Model):
    name = models.CharField(max_length=30)

    @staticmethod
    def autocomplete_search_field():
        return ('id__iexact', 'name__icontains',)

    def __str__(self):
        return '%s' % (self.name)

then in admin.py:

class EntryAdmin(admin.ModelAdmin):
    raw_id_fields = ('keywords',)
    autocomplete_lookup_fields = {
        'm2m': ['keywords'],
    }

class KeywordAdmin(admin.ModelAdmin):
    pass

admin.site.register(Entry, EntryAdmin)
admin.site.register(Keyword, KeywordAdmin)

Image showing that it isn't returning any results even though there's definitely a keyword entry titled 'Finances'.

Keyword Lookup with Grappelli M2M


Solution

  • The correct method name is autocomplete_search_fields, plural. In your Keyword model you're using autocomplete_search_field