[Fixed]-Django Many to Many Inline – how to show fields referenced by through model?

6👍

Try this. Hope it solves your problem

class ClownInline(admin.TabularInline):
    model = WorkedAt
    fields = ['clown_name', 'clown_edit_link']
    readonly_fields = ['clown_name', 'clown_edit_link']

    def clown_name(self, instance):
        return instance.clown.name
    clown_name.short_description = 'clow name'

    def clown_edit_link(self, instance):
        url = reverse("admin:%s_%s_change" % (instance.clown._meta.app_label, instance.clown._meta.module_name), args=(instance.clown.pk,))
        return '<a href="%s">%s</a>' % (url, instance.clown.name)
    clown_edit_link.allow_tags = True


class CircusAdmin(admin.ModelAdmin):
    inlines = [
        ClownInline,
    ]
    exclude = ('clowns',)
👤sj7

2👍

I don’t know if anyone still needs this, because this question is 4 years old but this solved my problem for in Django 2.0.3:

# models.py
class Clown(models.Model):
    name = models.CharField(max_length=255)
    def edit_link(self):
        return ...


class Circus(models.Model):
    clowns = models.ManyToManyField(Clown, blank=True, through='WorkedAt')
    name = models.CharField(max_length=255)


class WorkedAt(models.Model):
    clown = models.ForeignKey(Clown)
    circus = models.ForeignKey(Circus)


# admin.py
class WorkedAtInline(admin.TabularInline):
    model = WorkedAt
    extra = 1


class WorkedAtAdmin(admin.ModelAdmin):
    inlines = (WorkedAtInline,)


admin.site.register(Clown, WorkedAtAdmin)

Hope this helps anyone that stumbles upon this problem and looks into this answer.

Leave a comment