【问题标题】:Django ModelForm override widgetDjango ModelForm 覆盖小部件
【发布时间】:2012-04-10 07:57:10
【问题描述】:

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

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

#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')

在我的表单中带有选择框?以下是好的还是我错过了什么?

#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。

谢谢!

【问题讨论】:

    标签: django django-models


    【解决方案1】:

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

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

    例如,如果您希望 Author 的 name 属性的 CharField 由 <textarea> 表示,而不是其默认的 <input type="text">,您可以覆盖该字段的小部件:

    from django.forms import ModelForm, Textarea
    from myapp.models import Author
    
    class AuthorForm(ModelForm):
        class Meta:
            model = Author
            fields = ('name', 'title', 'birth_date')
            widgets = {
                'name': Textarea(attrs={'cols': 80, 'rows': 20}),
            }
    

    小部件字典接受小部件实例(例如,Textarea(...))或类(例如,Textarea)。

    https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/#overriding-the-default-fields

    【讨论】:

      猜你喜欢
      • 2019-08-22
      • 2011-03-28
      • 2016-03-20
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 2012-01-31
      相关资源
      最近更新 更多