Search code examples
djangodjango-widget

Specify Widget's class


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.


Solution

  • 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'