Django Admin - 覆盖自定义表单字段的小部件
我有一个自定义 TagField 表单字段。
class TagField(forms.CharField):
def __init__(self, *args, **kwargs):
super(TagField, self).__init__(*args, **kwargs)
self.widget = forms.TextInput(attrs={'class':'tag_field'})
如上所示,它使用 TextInput 表单字段小部件。但在管理中我希望它使用 Textarea 小部件显示。为此,有 formfield_overrides
挂钩,但它不适用于这种情况。
管理员声明是:
class ProductAdmin(admin.ModelAdmin):
...
formfield_overrides = {
TagField: {'widget': admin.widgets.AdminTextareaWidget},
}
这对表单字段小部件没有影响,并且 标签
仍然使用 TextInput 小部件呈现。
非常感谢任何帮助。
--
奥马特
I have a custom TagField form field.
class TagField(forms.CharField):
def __init__(self, *args, **kwargs):
super(TagField, self).__init__(*args, **kwargs)
self.widget = forms.TextInput(attrs={'class':'tag_field'})
As seen above, it uses a TextInput form field widget. But in admin I would like it to be displayed using Textarea widget. For this, there is formfield_overrides
hook but it does not work for this case.
The admin declaration is:
class ProductAdmin(admin.ModelAdmin):
...
formfield_overrides = {
TagField: {'widget': admin.widgets.AdminTextareaWidget},
}
This has no effect on the form field widget and tags
are still rendered with a TextInput widget.
Any help is much appreciated.
--
omat
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
django 管理员在其许多字段中使用自定义小部件。覆盖字段的方法是创建一个与 ModelAdmin 对象一起使用的表单。
然后,在 ModelAdmin 对象中,指定以下形式:
此时,您还可以覆盖查询集:例如,根据模型中的另一个字段过滤对象(因为
limit_choices_to
无法处理此问题)The django admin uses custom widgets for many of its fields. The way to override fields is to create a Form for use with the ModelAdmin object.
Then, in your ModelAdmin object, you specify the form:
You can also override the queryset at this time: to filter objects according to another field in the model, for instance (since
limit_choices_to
cannot handle this)从 Django 1.2 开始,您可以通过扩展
ModelForm
的Meta
类来覆盖字段小部件:https://docs.djangoproject.com/en/stable/topics/forms/modelforms/#overriding-the-default-fields
You can override field widgets by extending the
Meta
class of aModelForm
since Django 1.2:https://docs.djangoproject.com/en/stable/topics/forms/modelforms/#overriding-the-default-fields
对于特定字段而不是我使用的字段:
谢谢,@Murat Çorlu
For a specific field not a kind of fields I use:
Thanks, @Murat Çorlu
尝试像这样更改您的字段:
这将允许使用来自
**kwargs
的小部件。否则,您的字段将始终使用form.TextInput
小部件。Try to change your field like this:
This would allow to use the widget which comes from
**kwargs
. Otherwise your field will always useform.TextInput
widget.