I have this 3 models:
class MyFile(models.Model):
file = models.FileField(upload_to="files/%Y/%m/%d")
def __unicode__(self):
"""."""
return "%s" % (
self.file.name)
class ExampleModel(models.Model):
attached_files =models.ManyToManyField(MyFile)
main_model = models.ForeignKey(MainModel)
class MainModel(models.Model):
attached_files =models.ManyToManyField(MyFile)
And my admin.py as follows:
class ExampleModelAdminInline(admin.TabularInline):
model = ExampleModel
extra = 2
class MainModelAdmin(admin.ModelAdmin):
inlines = [ExampleModelAdminInline]
Im using django-grapelli because it offer autocomplete lookups for many to many fields. However, Im not sure how to add this autocomplete lookup to a TabularInline admin. Can anyone explain me how to set up the attached_files field to have autocomplete lookups?
First you need to set the static method
autocomplete_search_fields()in theModelyou want to search from, in your caseMyFile. From the docs we get:You can also define
GRAPPELLI_AUTOCOMPLETE_SEARCH_FIELDSinstead of declaring the static method, like:Then you should add the lookup and raw fields to your desired
adminclass, considering its relatedModel(say, yourExampleModel) which is the one that has aManyToManyField. You can also handleForeignKeyin a similar way. Also from the mentioned docs:Remember to register both ends (your models) of the relationship to your
admin.site, like this:You can also check this question to understand better.