如何为 Django ModelForm 设置默认小部件属性? [英] How do I set default widget attributes for a Django ModelForm?

查看:17
本文介绍了如何为 Django ModelForm 设置默认小部件属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 TextInput Widget 的 class 属性设置为表单中使用它的所有字段的一个值,而不必在 Meta 中列出所有字段:widgets = {.... 这可能吗?

谢谢.

解决方案

您可以重写构造函数以修改所有 TextInput 小部件:

from django 导入表单类 MyForm(forms.ModelForm):def __init__(self, *args, **kwargs):super(MyForm, self).__init__(*args, **kwargs)对于名称,self.fields.items() 中的字段:如果 field.widget.__class__ == forms.widgets.TextInput:如果 field.widget.attrs 中的类":field.widget.attrs['class'] += 'my-class'别的:field.widget.attrs.update({'class':'my-class'})元类:模型 = 我的模型

<块引用>

你能用装饰器覆盖 init 吗?此外,在 attrs.update() 之前应该有一个 if 语句,因为我想设置一个默认值而不是覆盖可能已经存在的内容.– 凯文

未经测试,但我想如果你经常使用它,你可以从 MyForm 继承.

I'd like to set the class attribute for the TextInput Widget to one value for all the fields in my form that use it without having to list them all in Meta: widgets = {.... Is this possible?

Thanks.

解决方案

You can override the constructor in order to modify all TextInput widgets:

from django import forms

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        for name, field in self.fields.items():
            if field.widget.__class__ == forms.widgets.TextInput:
                if 'class' in field.widget.attrs:
                    field.widget.attrs['class'] += ' my-class'
                else:
                    field.widget.attrs.update({'class':'my-class'})
    class Meta:
        model = MyModel

can you override init with a decorator? also, there should be an if statement before the attrs.update() becuase I want to set a default rather than override what may already be there. – Kevin

Untested, but I guess you can just inherit from MyForm if you use this a lot.

这篇关于如何为 Django ModelForm 设置默认小部件属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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