mel*_*low 30 django django-models
免责声明:我是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')
Run Code Online (Sandbox Code Playgroud)
在我的表格中有一个选择框?以下是好的还是我错过了什么?
#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)}
Run Code Online (Sandbox Code Playgroud)
在阅读https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets之后,由于该示例仅讨论TextArea和小部件讨论,因此我感到迷茫.似乎排除了ModelForm.
谢谢!
qri*_*ris 89
如果要覆盖一般表单的窗口小部件,最好的方法是设置类的widgets属性ModelForm Meta:
要为字段指定自定义窗口小部件,请使用内部Meta类的窗口小部件属性.这应该是将字段名称映射到窗口小部件类或实例的字典.
例如,如果您希望Author的name属性的CharField由a
<textarea>而不是默认值表示<input type="text">,则可以覆盖该字段的窗口小部件:Run Code Online (Sandbox Code Playgroud)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/dev/topics/forms/modelforms/#overriding-the-default-fields
| 归档时间: |
|
| 查看次数: |
34576 次 |
| 最近记录: |