Skip to content Skip to sidebar Skip to footer

Override Django ImageField Validation

I am trying to create a form where users will be allowed to upload any image file + SWF files. Django's ImageField does not support SWF so I need to override it. What I want to do

Solution 1:

An alternative and possibly easiest solution is to use a standard FileField with a custom validator:

def my_validate(value):
    ext = os.path.splitext(value.name)[1]  # [0] returns path filename
    valid = ['.jpg', '.swf']
    if ext not in valid:
        raise ValidationError("Unsupported file extension.")

class MyForm(forms.Form):
    file = forms.FileField(validators=[my_validate])

Solution 2:

may be it will be useful:

from django.core.validators import FileExtensionValidator


class MyModel(models.Model):
    ......
    my_field = models.FileField('Name', validators=[FileExtensionValidator(['svg', 'jpg', 'png', '.....'])])

Post a Comment for "Override Django ImageField Validation"