gpt4 book ai didi

django - 将参数传递给 django admin 中的内联表单

转载 作者:行者123 更新时间:2023-12-04 00:41:09 25 4
gpt4 key购买 nike

我有一个从 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

我想传递一个参数给 TemplateAttributeInline然后将参数传递给 TemplateAttributeForm .做这个的最好方式是什么?

模板属性内联:
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)

最佳答案

您可以创建一个返回表单类的函数:

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

在另一个函数中使用它来定义 TemplateAttributeInline
def TemplateAttributeInline(param):

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

return MyTemplateAttributeInline

最后,在您的 TemplateAdmin 中使用此功能定义:
class TemplateAdmin (admin.ModelAdmin):
inlines = (TemplateAttributeInline(param), CompanyAttributeInline)
....

关于django - 将参数传递给 django admin 中的内联表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30779959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com