1
我有自定義clean_*
表單方法,它可以驗證上傳的圖像類型和文件擴展名。在Django ModelForm中更改默認字段驗證器
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
它運作良好,直到適當格式的圖像,但沒有一個文件擴展名試圖上傳,在這種情況下default_validator
踢,我看到默認FileExtensionValidator
錯誤消息:
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'.
是有沒有辦法替換ModelForm
字段的default_validator
而不重新聲明字段?
您正在使用哪個版本的Django?您可能會發現[ticket#28242](https://code.djangoproject.com/ticket/28242),該問題在Django 1.11.2中已經修復。 – Alasdair
謝謝,我正在使用'(1,11,4,'final',0)',但不知道引用的tick如何幫助我? –