[Django]-How can I enable inline ManyToManyFields on my Django admin site?

32πŸ‘

It is quite simple to do what you want, If I am getting you correctly:

You should create an admin.py file inside your apps directory and then write the following code:

from django.contrib import admin
from myapps.models import Author, Book

class BookAdmin(admin.ModelAdmin):
     model= Book
     filter_horizontal = ('authors',) #If you don't specify this, you will get a multiple select widget.

admin.site.register(Author)
admin.site.register(Book, BookAdmin)
πŸ‘€Prateek

29πŸ‘

Try this:

class AuthorInline(admin.TabularInline):

    model = Book.authors.through
    verbose_name = u"Author"
    verbose_name_plural = u"Authors"


class BookAdmin(admin.ModelAdmin):

    exclude = ("authors", )
    inlines = (
       AuthorInline,
    )

You might need to add raw_id_fields = ("author", ) to AuthorInline if you have many authors.

8πŸ‘

πŸ‘€darren

Leave a comment