Python Django Admin:仅对一个模型字段使用自定义小部件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4176613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:38:04  来源:igfitidea点击:

Django Admin: Using a custom widget for only one model field

pythondjangodjango-formsdjango-admindjango-widget

提问by Belmin Fernandez

I have a DateTimeFieldfield 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 onlythis one field.

我的模型中有一个DateTimeField字段。我想将它显示为 Django 管理站点中的复选框小部件。为此,我创建了一个自定义表单小部件。但是,我不知道如何将我的自定义小部件用于这一领域。

The Django documentationexplains how to use a custom widget for allfields of a certain type:

Django文档解释了如何使用自定义窗口小部件的所有特定类型的字段:

class StopAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.DateTimeField: {'widget': ApproveStopWidget }
    }

This is not granular enough though. I want to change it for only onefield.

但这还不够细化。我只想为一个字段更改它。

采纳答案by Chris Pratt

Create a custom ModelForm for your ModelAdmin and add 'widgets' to its Meta class, like so:

为您的 ModelAdmin 创建一个自定义 ModelForm 并将“小部件”添加到其 Meta 类,如下所示:

class StopAdminForm(forms.ModelForm):
  class Meta:
    model = Stop
    widgets = {
      'approve_ts': ApproveStopWidget(),
    }
    fields = '__all__'

class StopAdmin(admin.ModelAdmin):
  form = StopAdminForm

Done!

完毕!

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

这方面的文档有点不直观地放在 ModelForm 文档中,在管理文档中没有提及它。请参阅:从模型创建表单

回答by Belmin Fernandez

After digging into the admin, model fieldand form fieldcode, I believe the only way to carry out what I want is by creating a custom model field:

在深入研究admin模型字段表单字段代码后,我相信实现我想要的唯一方法是创建自定义模型字段:

models.py

models.py

from django.db import models
from widgets import ApproveStopWidget

class ApproveStopModelField(models.DateTimeField):
    pass

class Stop(models.model):
    # Other fields
    approve_ts = ApproveStopModelField('Approve place', null=True, blank=True)

admin.py

admin.py

from widgets import ApproveStopWidget
from models import ApproveStopModelField

class StopAdmin(admin.ModelAdmin):
    formfield_overrides = {
        ApproveStopModelField: {'widget': ApproveStopWidget }
    }

It gets the job done.

它完成了工作。

For the time being, I'll leave the question unanswered because I have the habit of missing the obvious. Perhaps some Django smartypants has a better solution.

暂时,我不会回答这个问题,因为我有遗漏显而易见的习惯。也许一些 Django smartypants 有更好的解决方案。

回答by Arya-2790306

Django's ModelAdmin.get_changelist_form(self, request, **kwargs) will do the trick for the case of list_editable

Django 的 ModelAdmin.get_changelist_form(self, request, **kwargs) 将解决 list_editable 的问题

class StopAdminForm(forms.ModelForm):
  class Meta:
    model = Stop
    widgets = {
      'approve_ts': ApproveStopWidget(),
    }

class StopAdmin(admin.ModelAdmin):
  form = StopAdminForm

  #just return the ModelForm class StopAdminForm
  def get_changelist_form(self, request, **kwargs):
        return StopAdminForm

Refer to Django Official documentation on this topic

有关此主题,请参阅Django 官方文档

I hope this will help

我希望这个能帮上忙

回答by Andy Baker

Override formfield_for_dbfield like thus:

像这样覆盖 formfield_for_dbfield:

class VehicleAdmin(admin.ModelAdmin):
    search_fields = ["name", "colour"]

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'colour':
            kwargs['widget'] = ColourChooserWidget
        return super(VehicleAdmin, self).formfield_for_dbfield(db_field,**kwargs)

(credit to http://www.kryogenix.org/days/2008/03/28/overriding-a-single-field-in-the-django-admin-using-newforms-admin/)

(归功于http://www.kryogenix.org/days/2008/03/28/overriding-a-single-field-in-the-django-admin-using-newforms-admin/