Django Admin:仅对一个模型字段使用自定义小部件 [英] Django Admin: Using a custom widget for only one model field

查看:27
本文介绍了Django Admin:仅对一个模型字段使用自定义小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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 Admin:仅对一个模型字段使用自定义小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆