Django ModelForm 覆盖小部件 [英] Django ModelForm override widget
问题描述
免责声明:我是 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 由 表示,而不是其默认的
,您可以覆盖该字段的小部件:
For example, if you want the a CharField for the name attribute of Author to be represented by a <textarea>
instead of its default <input type="text">
, you can override the field’s widget:
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).
The widgets dictionary accepts either widget instances (e.g., Textarea(...)) or classes (e.g., Textarea).
https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/#overriding-the-default-fields
这篇关于Django ModelForm 覆盖小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!