创建的表单元素的宽度

创建的表单元素的宽度

本文介绍了更改在 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.它是一种用于定义表示的语言.查看表单生成的代码,记下您感兴趣的字段的 id,并通过 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

在 Django 文档中有所描述.

第三种方法是暂时离开 newforms 的漂亮声明式界面,并在自定义构造函数中设置您的小部件属性.

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 创建的表单元素的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!