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

2👍

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.

3👍

To display the ISBN you could make a custom field like this:


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

There’s a CheckboxSelectMultiple for the ManyToManyField but it doesn’t display correctly on the admin, so you could also write some css to fix that.

You need to create a form for the model, and use that 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

Leave a comment