Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to inline form in django admin

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)
like image 459
Oscar Robinson Avatar asked Feb 10 '23 21:02

Oscar Robinson


1 Answers

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)
    ....
like image 129
Sylvain Biehler Avatar answered Feb 13 '23 22:02

Sylvain Biehler