2012-03-26 55 views
18

声明:我是一名初学者,拥有python和Django,但拥有Drupal编程经验。初学者:Django ModelForm替代小部件

我如何可以覆盖这个默认的窗口小部件:

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

谢谢!

回答

58

如果要覆盖在一般formfield小部件,最好的办法是设置ModelForm Meta类的widgets属性:

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

例如,如果你想在一个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/dev/topics/forms/modelforms/#overriding-the-default-fields