Django管理员:仅为一个模型字段使用自定义小部件 [英] Django Admin: Using a custom widget for only one model field
问题描述
我有一个 DateTimeField 字段在我的模型。我想在Django管理员网站中显示为复选框小部件。为此,我创建了一个自定义表单小部件。但是,我不知道如何使用我的自定义小部件仅此一个字段。
I have a DateTimeField field in my model. I wanted to display it as a checkbox widget in the Django admin site. To do this, I created a custom form widget. However, I do not know how to use my custom widget for only this one field.
Django文档解释了如何使用自定义小部件所有的某些类型的字段:
The Django documentation explains how to use a custom widget for all fields of a certain type:
class StopAdmin(admin.ModelAdmin):
formfield_overrides = {
models.DateTimeField: {'widget': ApproveStopWidget }
}
没有足够的粒度。我想要更改它仅一个字段。
This is not granular enough though. I want to change it for only one field.
推荐答案
为您的ModelAdmin创建一个自定义ModelForm,添加'小部件'到它的Meta类,像这样:
Create a custom ModelForm for your ModelAdmin and add 'widgets' to its Meta class, like so:
class StopAdminForm(forms.ModelForm):
class Meta:
model = Stop
widgets = {
'approve_ts': ApproveStopWidget(),
}
fields = '__all__'
class StopAdmin(admin.ModelAdmin):
form = StopAdminForm
完成!
这是一种非直观地放在ModelForm文档中的文档,在管理文档中没有提及它。请参阅:创建表单来自模型
Documentation for this is sort of non-intuitively placed in the ModelForm docs, without any mention to it given in the admin docs. See: Creating forms from models
这篇关于Django管理员:仅为一个模型字段使用自定义小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!