Passing parameters to inline form in django admin

有些话、适合烂在心里 提交于 2019-12-22 17:52:27

问题


I have an admin class inheriting from ModelAdmin:

class TemplateAdmin (admin.ModelAdmin):
    inlines = (TemplateAttributeInline, CompanyAttributeInline)
    list_display = ("name", "created", "updated","departments")
    list_filter = ['companies__company']
    list_editable = ("departments",)
    search_fields = ("name", "companies__company",)
    exclude = ("companies",)
    save_as = True

I want to pass a parameter to TemplateAttributeInline which will in turn then pass the parameter to TemplateAttributeForm. What is the best way to do this?

TemplateAttributeInline:

class TemplateAttributeInline (admin.TabularInline):
    model = TemplateAttribute
    extra = 0
    sortable_field_name = "display"
    form = TemplateAttributeForm

TemplateAttributeForm

class TemplateAttributeForm(forms.ModelForm):
    class Meta:
        model = Template
    def __init__(self,*args, **kwargs):
        super(TemplateAttributeForm, self).__init__(*args, **kwargs) 
        self.fields['attribute'].queryset = Attribute.objects.filter(#WANT TO FILTER BY THE ID OF THE COMPANY THAT OWNS THE TEMPLATE WE ARE EDITING ON THE ADMIN PAGE)

回答1:


You can create a function that returns a class for the form:

def TemplateAttributeForm(param):

    class MyTemplateAttributeForm(forms.ModelForm):
        class Meta:
            model = Template
        def __init__(self,*args, **kwargs):
            super(TemplateAttributeForm, self).__init__(*args, **kwargs) 
            #do what ever you want with param

    return MyTemplateAttributeForm

Use it in another funtion to define the TemplateAttributeInline

def TemplateAttributeInline(param):

        class MyTemplateAttributeInline (admin.TabularInline):
            model = TemplateAttribute
            extra = 0
            sortable_field_name = "display"
            form = TemplateAttributeForm(param)

        return MyTemplateAttributeInline 

To finish, use this function in your TemplateAdmin definition:

class TemplateAdmin (admin.ModelAdmin):
    inlines = (TemplateAttributeInline(param), CompanyAttributeInline)
    ....


来源:https://stackoverflow.com/questions/30779959/passing-parameters-to-inline-form-in-django-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!