Search code examples
pythondjangodjango-admindjango-widget

In Django Admin, I want to change how foreign keys are displayed in a Many-Many Relationship admin widget


I have a ManyToMany relationship:

class Book:
  title = models.CharField(...)
  isbn = models.CharField(...)

  def unicode(self):
    return self.title

  def ISBN(self):
    return self.isbn

class Author:
  name = models.CharField(...)
  books = models.ManyToManyField(Book...)

In the admin interface for Author I get a multiple select list that uses the unicode display for books. I want to change the list in two ways:

1) Only for the admin interface I want to display the ISBN number, everywhere else I just print out a "Book" object I want the title displayed.

2) How could I use a better widget than MultipleSelectList for the ManyToMany. How could I specify to use a CheckBoxSelectList instead?


Solution

  • For 2), use this in your AuthorAdmin class:

    raw_id_fields = ['books']
    

    Check here: http://docs.djangoproject.com/en/dev/ref/contrib/admin/#ref-contrib-admin for instructions on creating a custom ModelAdmin class. I've thought about this a lot myself for my own Django project, and I think 1) would require modifying the admin template for viewing Author objects.