Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

My models are

class Test(models.Model):
    name = models.CharField(max_length=255)

class Testrelated(models.Model):
    name = models.CharField(max_length=255)
    tests = models.ManyToManyField(Test, related_name='tests')

And admin:

class TestrelatedInline(admin.TabularInline):
    extra = 0
    model = models.Test.tests.through
    filter_horizontal = ('name')

class TestAdmin(admin.ModelAdmin):
    list_display = ('id', 'name')
    search_fields = ('name',)

    inlines = [
        TestrelatedInline,
    ]

The problem is that .through has no the model fields. So I can not refer to any field using filter_horizontal.

<class 'app.admin.TestrelatedInline'>: (admin.E019) The value of 'filter_horizontal[0]' refers to 'name', which is not an attribute of 'app.Testrelated_tests'.

I have created a test stand https://gitlab.com/marataziat/testdjangoproject.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

You don't need an inline admin in your case. filter_horizontal mechanism is designed to handle many-to-many relations via multiple selection widget in its own admin page.

If you want to use tabular inline and insert extra when needed, you can override TabularInline's formfield_for_foreignkey to define queryset and widget.

class TestrelatedInline(admin.TabularInline):
    extra = 0
    model = models.Test.tests.through
    
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "testrelated":
            kwargs["queryset"] = models.Testrelated.objects.all()
            kwargs["widget"] = Select(attrs={"style": "width:400px"},)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...