Django Admin中的动态字段 [英] Dynamic fields in Django Admin
问题描述
我想要有一个字段的值的附加字段。因此,我建立一个自定义的管理表单来添加一些新的领域。
I want to have additional fields regarding value of one field. Therefor I build a custom admin form to add some new fields.
与jacobian的博客相关 1 这是我想出的:
Related to the blogpost of jacobian 1 this is what I came up with:
class ProductAdminForm(forms.ModelForm):
class Meta:
model = Product
def __init__(self, *args, **kwargs):
super(ProductAdminForm, self).__init__(*args, **kwargs)
self.fields['foo'] = forms.IntegerField(label="foo")
class ProductAdmin(admin.ModelAdmin):
form = ProductAdminForm
admin.site.register(Product, ProductAdmin)
但是,附加字段foo不会显示在管理员中。如果我添加这样的字段,一切都可以正常工作,但不如所需的动态,添加关于模型的另一个字段的值的字段
But the additional field 'foo' does not show up in the admin. If I add the field like this, all works fine but is not as dynamic as required, to add the fields regarding the value of another field of the model
class ProductAdminForm(forms.ModelForm):
foo = forms.IntegerField(label="foo")
class Meta:
model = Product
class ProductAdmin(admin.ModelAdmin):
form = ProductAdminForm
admin.site.register(Product, ProductAdmin)
是否有任何初始化方法,我必须再次触发,使新的字段工作?还是有任何其他尝试?
So is there any initialize method that i have to trigger again to make the new field working? Or is there any other attempt?
推荐答案
这是解决问题的方法。感谢koniiiik,我尝试通过扩展* get_fieldsets *方法来解决这个问题。
Here is a solution to the problem. Thanks to koniiiik i tried to solve this by extending the *get_fieldsets* method
class ProductAdmin(admin.ModelAdmin):
def get_fieldsets(self, request, obj=None):
fieldsets = super(ProductAdmin, self).get_fieldsets(request, obj)
fieldsets[0][1]['fields'] += ['foo']
return fieldsets
如果您使用多个字段,请确保添加通过使用适当的索引到正确的字段集。
If you use multiple fieldsets be sure to add the to the right fieldset by using the appropriate index.
这篇关于Django Admin中的动态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!