Specify Widget's class

為{幸葍}努か 提交于 2019-12-11 00:23:06

问题


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.


回答1:


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)

And then use CustomImagePreviewWidget in your forms.

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'


来源:https://stackoverflow.com/questions/33457665/specify-widgets-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!