Search code examples
djangodjango-modelsdjango-formsdjango-widget-tweaks

Can django widget_tweaks render out input as textarea box?


I want to render out an input box as textarea with widget_tweaks in Django.

This is my code:

                <div class="form-row">
                <div class="form-group col-md-6">
                    <label>More information *</label>
                    {% render_field form.info class="form-control" %}
                </div>                
            </div>

Everything is working fine, but it renders out as <input> tag. Is there any way to render it out as <textarea> without changing the models from CharField to TextField? I want to have a bigger box so there is more space to write the text. I know I can add a class that could change the size of the input box, but the textarea tag would be easier.


Solution

  • You can render CharField as textarea by specifying widget in your forms.py.

    text = forms.CharField(widget=forms.Textarea)
    

    or to set default width and height of textarea

    text = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":10}))
    
    

    There are two ways to incorporate this to your forms.py.

    1. preferred way especially if you want to add widgets to multiple fields.
    class MyModelForm(forms.ModelForm):
    
        class Meta:
            model = MyModel
            fields= ('text', 'field2')
            widgets = {
                'text': forms.Textarea(attrs={"rows":3, "cols":10})),
                'field2': forms.RadioSelect(attrs= {
                     'class': 'choice_class'})
            }
    

    Note that although widget can add class, I think it is better to add css class or id using widget-tweaks at template level rather than widget.

    1. another way in forms.py. This way works well when you want to add widgets to one or two fields.
    class MyModelForm(forms.ModelForm):
        text = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":10})
    
        class Meta:
             model = MyModel
             fields = ('text', 'field2',)