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.
If you want the class to be there in all instances of the widget, you can override (or modify) the widget's
render
method:And then use
CustomImagePreviewWidget
in your forms.Looking at it some more, you can also do this in the widget's
__init__
method: