In Django Admin, I want to change how foreign keys are displayed in the 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 multi-select list that uses the unicode screen for books. I want to change the list in two ways:

1) For the admin interface only, I want to display the ISBN, everywhere I just print the Book object. I want the title to be displayed.

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

+2


source to share


2 answers


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 how to create a custom ModelAdmin class. I've thought about this a lot for my own Django project and I think 1) will need to change the admin template to view Author objects.

+1


source


To display the ISBN, you can create a custom field as follows:


class BooksField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return obj.isbn

      

There have CheckboxSelectMultiple for a ManyToManyField, but it does not appear correctly for the administrator, so you can also write css to fix it.



You need to create a form for the model and use it in your admin class:


class AuthorForm(forms.ModelForm):
    books = BooksField(Book.objects.all(), widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Author

    class Media:
        css = {
            'all': ('booksfield.css',)
        }

class AuthorAdmin(admin.ModelAdmin):
    form = AuthorForm

      

+2


source







All Articles