Django:override RelatedFieldWidgetWrapper [英] Django: override RelatedFieldWidgetWrapper
问题描述
我想改变管理员网站中外键的+图标的显示方式。
I want to change the way that the "+" icon for the foreign key in the admin site is shown.
我发现打印代码的窗口小部件是 RelatedFieldWidgetWrapper
,它位于 django / contrib / admin / widgets.py
中。
I found that the widget that prints the code is RelatedFieldWidgetWrapper
that is in django/contrib/admin/widgets.py
.
所以我写了我的这个类的版本,我改变了它的 render
函数。
So I wrote my version of this class and I changed its render
function.
但是现在我该怎么用呢?我的意思是...在我的模型的定义中,我必须以这种方式使用 formfield_overrides
But now how can I use it? I mean... in the definition of my model do I have to use the formfield_overrides
in this way?
formfield_overrides = {
models.ForeignKey: {'widget': customRelatedFieldWidgetWrapper},
}
我认为这不是正确的方法,因为该小部件不是管理整个外键的部件,而只是+图标。
我错了?
I think that this is not the right way, because that widget is not the one that manage the whole foreign key, but only the "+" icon. Am I wrong?
非常感谢
推荐答案
p>您需要为ModelAdmin创建自定义ModelForm并覆盖其中的小部件。
You would need to create custom ModelForm for ModelAdmin and override widget there.
示例代码:
#forms.py
class CustomForm(forms.ModelForm):
user = forms.ModelChoiceField(queryset=User.objects.all(), widget=yourCustomWidget)
class Meta:
model = MyModel
#admin.py
class MyModelAdmin(admin.ModelAdmin):
form = CustomForm
这篇关于Django:override RelatedFieldWidgetWrapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!