Django ModelForm 覆盖小部件 [英] Django ModelForm override widget

查看:44
本文介绍了Django ModelForm 覆盖小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我是 Python 和 Django 的初学者,但有 Drupal 编程经验.

Disclaimer: I am a beginner with python and Django but have Drupal programming experience.

我怎样才能覆盖这个的默认小部件:

How can I override the default widget of this:

#models.py
class Project(models.Model):
color_mode = models.CharField(max_length=50, null=True, blank=True, help_text='colors - e.g black and white, grayscale')

在我的表单中带有选择框?以下内容是否正常,还是我遗漏了什么?

in my form with a select box? Is the following OK or am I missing something?

#forms.py
from django.forms import ModelForm, Select
class ProjectForm(ModelForm):
    class Meta:
        model = Project
        fields = ('title', 'date_created', 'path', 'color_mode')
        colors = (
                   ('mixed', 'Mixed (i.e. some color or grayscale, some black and white)'),
                   ('color_grayscale', 'Color / Grayscale'),
                   ('black_and_white', 'Black and White only'),
                   )
        widgets = {'color_mode': Select(choices=colors)}

阅读后https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets,我迷路了,因为这个例子只讨论了 TextArea 而小部件的讨论似乎排除 ModelForm.

After reading https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets, I am lost since the example only discusses TextArea and the widgets discussion seems to exclude ModelForm.

谢谢!

推荐答案

如果您想覆盖一般表单域的小部件,最好的方法是设置 widgets 属性>ModelForm Meta 类:

If you want to override the widget for a formfield in general, the best way is to set the widgets attribute of the ModelForm Meta class:

要为字段指定自定义小部件,请使用内部 Meta 类的小部件属性.这应该是一个将字段名称映射到小部件类或实例的字典.

To specify a custom widget for a field, use the widgets attribute of the inner Meta class. This should be a dictionary mapping field names to widget classes or instances.

例如,如果您希望 Author 的 name 属性的 CharField 由