Django ModelForm覆盖小部件 [英] Django ModelForm override widget
问题描述
免责声明:我是python和Django的初学者,但是有Drupal编程经验。
Disclaimer: I am a beginner with python and Django but have Drupal programming experience.
如何覆盖此默认控件:
#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,而小部件的讨论似乎
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.
谢谢!
推荐答案
如果要覆盖一般而言,最好是在 ModelForm Meta
类的 widgets
属性中进行设置:
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类的widgets属性。这应该是一个将字段名称映射到窗口小部件类或实例的字典。
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用< textarea>
而不是默认的< input type = text>
,您可以覆盖该字段的小部件:
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).
这篇关于Django ModelForm覆盖小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!