Change the width of form elements created with ModelForm in Django

后端 未结 4 1612
醉话见心
醉话见心 2020-12-22 19:13

How can I change the width of a textarea form element if I used ModelForm to create it?

Here is my product class:

class ProductForm(ModelForm):
    l         


        
4条回答
  •  梦毁少年i
    2020-12-22 19:57

    Excellent answer by zuber, but I believe there's an error in the example code for the third approach. The constructor should be:

    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor
        self.fields['long_desc'].widget.attrs['cols'] = 10
        self.fields['long_desc'].widget.attrs['cols'] = 20
    

    The Field objects have no 'attrs' attributes, but their widgets do.

提交回复
热议问题