2012-08-10 95 views
1

使用django.contrib.comments,我定义了一个自定义评论应用程序。我想覆盖文本区域小部件,使文本框看起来更小。Django Contrib评论:如何覆盖评论的textarea小部件?

所以我创建的是:

#forms.py 
class CustomCommentForm(CommentForm): 
    #...otherstuff... 

    comment = forms.CharField(label=_('Comment'), 
     widget=forms.Textarea(attrs={'rows':4}), 
     max_length=COMMENT_MAX_LENGTH) 

但我真的不希望有重新定义注释字段。我只想重新定义该字段使用的小部件。也就是说,它似乎只有ModelForms可以做的:

class Meta: 
    widgets = { 
     'comment': Textarea(attrs={'rows': 4}), 
    } 

有没有一种方法来重新定义小部件而不重新定义字段?或者我应该只使用CSS设置高度?

+3

我会使用CSS - 快速和优雅。 – Thomas 2012-08-10 12:23:41

回答

1

对于模型表格的Meta类,您只能使用widgets选项。

但是,您不需要重新定义整个comment字段。相反,请覆盖表单的__init__方法并在那里更改字段的widget

class CustomCommentForm(CommentForm): 
    #...otherstuff... 

    def __init__(self, *args, **kwargs): 
     super(CustomCommentForm, self).__init__(*args, **kwargs) 
     self.fields['comment'].widget = forms.Textarea(attrs={'rows':4})