更改Django中使用ModelForm创建的表单元素的宽度 [英] Change the width of form elements created with ModelForm in Django

查看:128
本文介绍了更改Django中使用ModelForm创建的表单元素的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用ModelForm创建它,我如何更改textarea表单元素的宽度?

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

这是我的产品类:

class ProductForm(ModelForm):
    long_desc = forms.CharField(widget=forms.Textarea)
    short_desc = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = Product

模板代码...

{% for f in form %}
    {{ f.name }}:{{ f }}
{% endfor %}

f 是实际的表单元素...

f is the actual form element...

推荐答案

您的用例最简单的方法是使用CSS 。这是一种用于定义演示文稿的语言。看看窗体生成的代码,记下感兴趣的字段的ids,并通过CSS更改这些字段的外观。

The easiest way for your use case is to use CSS. It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS.

ProductForm中的long_desc 字段(当您的表单没有自定义前缀时):

Example for long_desc field in your ProductForm (when your form does not have a custom prefix):

#id_long_desc {
    width: 300px;
    height: 200px;
}

第二种方法是通过 attrs 关键字到您的小部件构造函数。

Second approach is to pass the attrs keyword to your widget constructor.

class ProductForm(ModelForm):
    long_desc = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 20}))
    short_desc = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = Product

这是

It's described in Django documentation.

第三种方法是将新形式的漂亮的声明性界面暂时放置一段时间,并在自定义构造函数中设置您的小部件属性。

Third approach is to leave the nice declarative interface of newforms for a while and set your widget attributes in custom constructor.

class ProductForm(ModelForm):
    long_desc = forms.CharField(widget=forms.Textarea)
    short_desc = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = Product

    # Edit by bryan
    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['rows'] = 20

此方法具有以下优点:


  • 您可以为模型自动生成的字段定义窗口小部件属性,而无需重新定义整个字段。

  • 它不依赖于窗体的前缀。

这篇关于更改Django中使用ModelForm创建的表单元素的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆