11

I'm using a Django admin StackedInline, as follows:

class BookInline(admin.StackedInline):
    model = Book.subject.through
    verbose_name = 'Book'
    verbose_name_plural = 'Books with this subject'

class SubjectAdmin(admin.ModelAdmin):
    inlines = [
        BookInline,
    ]

It all works, but the header is pretty ugly:

Books With This Subject
Book: Book_subject object

Anyone know how I can get rid of, or change, the Book_subject object part?

thanks!

Serjik
  • 10,543
  • 8
  • 61
  • 70
AP257
  • 89,519
  • 86
  • 202
  • 261
  • The answer might be here: http://stackoverflow.com/questions/5086537/how-to-omit-object-name-from-djangos-tabularinline-admin-view – Vajk Hermecz Apr 16 '14 at 10:07

2 Answers2

12

I've never used an m2m field like this, so thanks! Learned something new.

I found 2 ways to get around the problem:

1: simply reassign the __unicode__ function with a new function

class MyInline(admin.TabularInline):
    MyModel.m2m.through.__unicode__ = lambda x: 'My New Unicode'
    model = MyModel.m2m.through

2: set up a proxy model for the m2m.through model and use that model instead

class MyThrough(MyModel.m2m.through):
    class Meta:
        proxy = True
    def __unicode__(self):
        return "My New Unicode"

class MyInline(admin.TabularInline):
    model = MyThrough
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • Ah, both my `Book` and my `Subject` models already have a `__unicode__` method defined. However, this is using `Book.subject.through` (subject is a ManyToManyField on Book) so I don't think there's any unicode method to define. Any ideas how I can get round this? – AP257 Feb 08 '11 at 10:23
  • I didn't even know you could do that with m2m, thanks! Yes, found a solution. updating – Yuji 'Tomita' Tomita Feb 08 '11 at 14:53
3

For some reason, the (admittedly now old) accepted answer did not work for me.

This modification, however, did change the header:

MyModel.field.through.__str__ = lambda x: 'New Title'

Where field is the ManyToMany field.

alstr
  • 1,358
  • 18
  • 34