指定小部件的类 [英] Specify Widget's class

查看:154
本文介绍了指定小部件的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用自定义小部件的字段的自定义表单。我需要设置小部件的类,目前我只能这样做:

I have a custom form with a field using a custom widget. I need to set the class of the widget, and currently I can only do it like this:

class DesignCampaignForm(ModelForm):

    brand_logo = FileField(widget=ImagePreviewWidget)
    brand_logo.widget.attrs['class'] = 'image-preview'

这意味着对于每个这样声明的小部件,我需要两行,并且一直重复该类 - 不是很干。

This means that for each widget declared like this I need two lines, and to repeat the class all the time - not very DRY.

有没有办法在窗口小部件本身中指定窗口小部件类?我在文档中找不到。

Is there a way to specify the widget class in the widget itself? I have been unable to find that in the documentation.

推荐答案

如果您希望该类在窗口小部件的所有实例中都可以,您可以覆盖(或修改)窗口小部件的 render 方法:

If you want the class to be there in all instances of the widget, you can override (or modify) the widget's render method:

class CustomImagePreviewWidget(ImagePreviewWidget):

    def render(self, name, value, attrs={}):
        attrs['class'] = 'image-preview'
        return super(CustomImagePreviewWidget, self).render(name, value, attrs)

然后在表单中使用 CustomImagePreviewWidget

再看一下,您还可以在小部件的 __ init __ 方法中执行此操作:

Looking at it some more, you can also do this in the widget's __init__ method:

class CustomImagePreviewWidget(ImagePreviewWidget):

    def __init__(self, attrs=None):
        super(CustomImagePreviewWidget, self).__init__(attrs)
        self.attrs['class'] = 'image-preview'

这篇关于指定小部件的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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