Understand I can add a validator to Django's ImageField validators to restrict file extension types like below. But in terms of the error messages which are displayed via upload on Admin -- I'm still seeing the standard file type list (via PIL allowed types), if I upload a non-image type. If I upload an image type which is not in my custom allowed_extensions below, I see my custom message. How can I override Django's default ImageField handling, and show my custom error message no matter what type of file is uploaded (e.g. when any file other than .png is uploaded per below example)?
class MM(models.Model):
file_extension_validator = FileExtensionValidator(
allowed_extensions=['png'],
message='File extension not allowed. Allowed extensions include .png'
)
image = models.ImageField(
help_text='Upload images only (.png).',
validators=[file_extension_validator],
max_length=255,
blank=False,
null=False
)
CodePudding user response:
The problem is not the model field, but the form field. The form field has a default validator that lists all the extensions PIL supports.
You can make a special form field ModifiedImageField
and specify that for the ModelForm
that will be used by the MyModelAdmin
in this case:
from django.contrib import admin
from django.core.validators import FileExtensionValidator
from django import forms
image_validator = FileExtensionValidator(
allowed_extensions=['png'],
message='File extension not allowed. Allowed extensions include .png'
)
class ModifiedImageField(forms.ImageField):
default_validators = [image_validator]
class MyModelAdminForm(forms.ModelForm):
imagefield = ModifiedImageField()
class MyModelAdmin(admin.ModelAdmin):
form = MyModelAdminForm
where imagefield
is the name of the ImageField
for which you want to replace the validator.