在Django Admin中访问内嵌get_formset中的内嵌字段

gmol1639  于 2022-12-24  发布在  Go
关注(0)|答案(1)|浏览(182)

bounty将在5天后过期。回答此问题可获得+50的声望奖励。drec4s正在寻找规范答案

我有下面的例子,我有建筑物(地址,位置,...)和公寓(名称,大小,类型,建筑物)。

class BuildingAdmin(admin.ModelAdmin):
    inlines = [ApartmentInline,]

class ApartmentInline(admin.StackedInline):
    def get_formset(self, request, obj=None, **kwargs):
        formset = super(ApartmentInline, self).get_formset(request, obj=None, **kwargs)

        #Here i'd like to see the values of inline fields, for example size or building that.
        #Similar to how one can access ModelAdmin fields with obj.location within get_form

        formset.form.base_fields["type"].widget = SelectMultiple(choices=custom_choices)
        return formset

我希望能够在编辑对象(例如大小)时获得当前公寓示例和字段值,以便我可以为另一个字段(类型)创建自定义选择(查询其他DB或API)。

krcsximq

krcsximq1#

访问与InlineModelAdmin(或它的子类)关联的模型示例是不可能的,您可以做的最接近的事情是为您的InlineModelAdmin创建一个定制的ModelForm
1.创建一个新的模型表单-ApartmentInlineForm

# forms.py

class ApartmentInlineForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance:
            self.base_fields["type"].widget = SelectMultiple(choices=(("Foo", "Bar"),))

    class Meta:
        model = Apartment
        fields = "__all__"

1.在内联模型类中使用ApartmentInlineForm

# admin.py

class ApartmentInline(admin.StackedInline):
    model = Apartment
    form = ApartmentInlineForm

1.注册您的Building型号

# admin.py

@admin.register(Building)
class BuildingAdmin(admin.ModelAdmin):
    inlines = [ApartmentInline]

相关问题