Django Admin - 覆盖自定义表单字段的小部件 [英] Django Admin - Overriding the widget of a custom form field
问题描述
我有一个自定义TagField表单域。
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'})
如上所示,它使用一个TextInput表单字段小部件。但是在管理员中,我希望它使用Textarea小部件显示。为此,有 formfield_overrides
钩子,但这不适用于这种情况。
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.
管理声明是: / p>
The admin declaration is:
class ProductAdmin(admin.ModelAdmin):
...
formfield_overrides = {
TagField: {'widget': admin.widgets.AdminTextareaWidget},
}
这没有对表单字段小部件的影响和标签
仍然使用TextInput小部件呈现。
This has no effect on the form field widget and tags
are still rendered with a TextInput widget.
任何帮助都非常感谢。
Any help is much appreciated.
-
omat
--
omat
推荐答案
django管理员使用许多领域的自定义小部件。重写字段的方法是创建一个用于ModelAdmin对象的表单。
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.
# forms.py
from django import forms
from django.contrib import admin
class ProductAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ProductAdminForm, self).__init__(*args, **kwargs)
self.fields['tags'].widget = admin.widgets.AdminTextareaWidget()
然后,在您的ModelAdmin对象中,指定以下格式:
Then, in your ModelAdmin object, you specify the form:
from django.contrib import admin
from models import Product
from forms import ProductAdminForm
class ProductAdmin(admin.ModelAdmin):
form = ProductAdminForm
admin.site.register(Product, ProductAdmin)
你也可以在此时覆盖查询集:根据模型中的另一个字段过滤对象(因为 limit_choices_to
不能处理这个)
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 Admin - 覆盖自定义表单字段的小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!