Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's say I have Books and Author models.

class Author(models.Model):     name = CharField(max_length=100)  class Book(models.Model):     title = CharField(max_length=250)     authors = ManyToManyField(Author) 

I want each Book to have multiple Authors, and on the Django admin site I want to be able to add multiple new authors to a book from its Edit page, in one go. I don't need to add Books to authors.

Is this possible? If so, what's the best and / or easiest way of accomplishing it?

like image 924
Alistair Avatar asked Feb 03 '11 10:02

Alistair


People also ask

What we can do in admin portal in Django?

Overview. The Django admin application can use your models to automatically build a site area that you can use to create, view, update, and delete records. This can save you a lot of time during development, making it very easy to test your models and get a feel for whether you have the right data.

How do I access my Django admin page?

If needed, run the Django app again with python manage.py runserver 0.0. 0.0:8000 and then navigate once more to the URL http:// your-server-ip :8000/admin/ to get to the admin login page. Then log in with the username and password and password you just created.

What is Admin ModelAdmin in Django?

One of the most powerful parts of Django is the automatic admin interface. It reads metadata from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin's recommended use is limited to an organization's internal management tool.


1 Answers

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) 
like image 96
Prateek Avatar answered Oct 20 '22 01:10

Prateek