NarūnasK
NarūnasK

Reputation: 4950

Changing default field validator in Django ModelForm

I have custom clean_* form method, which does verify uploaded image type and file extension.

class TableModelForm(ModelForm):
    def clean_image(self):
        img_err = 'Unsupport image type. Please upload png, jpg or gif.'
        img_formats = ['png', 'jpeg', 'gif']
        img = self.cleaned_data.get('image')
        if not img:
            return img
        img_fmt = img.image.format.lower()
        img_ext = splitext(img.name)[1][1:].lower()
        if any([x not in img_formats for x in [img_fmt, img_ext]]):
            raise ValidationError(ugettext_lazy(img_err), code='invalid_image')
        return img

It works well until the image of the appropriate format but without a file extension is attempted to upload, in which case default_validator kicks in and I see the default FileExtensionValidator error message:

File extension '' is not allowed. Allowed extensions are: 'bmp, bufr, cur, pcx, dcx, dds, ps, eps, fit, fits, fli, flc, fpx, ftc, ftu, gbr, gif, grib, h5, hdf, png, jp2, j2k, jpc, jpf, jpx, j2c, icns, ico, im, iim, tif, tiff, jfif, jpe, jpg, jpeg, mic, mpg, mpeg, mpo, msp, palm, pcd, pdf, pxr, pbm, pgm, ppm, psd, bw, rgb, rgba, sgi, ras, tga, webp, wmf, emf, xbm, xpm'.

Is there a way to replace the default_validator of the ModelForm field without re-declaring the field?

Upvotes: 1

Views: 680

Answers (1)

Alasdair
Alasdair

Reputation: 308939

I would try setting the field's validators to an empty list in the form's __init__ method.

class TableModelForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['image'].validators = []

Another option might be to subclass ImageField and change default_validators, then use your custom field in the model form.

I'm not really familiar with the internals of the file field and image field, so I'm not certain whether either approach will work.

Upvotes: 1

Related Questions