powlo
powlo

Reputation: 2708

Django Contrib Comments: How to override the comment's textarea widget?

Using django.contrib.comments, I've defined a custom comment app. I wanted to override the text area widget so that the textbox appears smaller.

So what I created was this:

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

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

But really I don't want to have to redefine the comment field. I want to just redefine the widget that's used by the field. Ie something that it seems only ModelForms can do:

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

Is there a way to redefine the widget without redefining the field? Or should I just set the height using CSS?

Upvotes: 1

Views: 528

Answers (1)

Alasdair
Alasdair

Reputation: 308999

You are correct that you can only use the widgets option for a model form's Meta class.

However you don't need to redefine the entire comment field. Instead, override the form's __init__ method and change the field's widget there.

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

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

Upvotes: 1

Related Questions