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)
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)
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With