Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A form field to handle validation of image + svg.
from xml.etree import cElementTree as et
from django.core.exceptions import ValidationError
from django.forms import ImageField
class SVGImageField(ImageField):
"""A Django ImageField that accepts SVG images."""
def to_python(self, data):
Check that the file-upload field data contains a valid image
(GIF, JPG, PNG, etc. -- whatever Pillow supports) or a SVG image.
file = super(SVGImageField, self).to_python(data)
except ValidationError as err:
# add a workaround to handle svg images
if not self.is_svg(file):
raise ValidationError(
) from err
file = super(ImageField, self).to_python(data)
file.content_type = 'image/svg+xml'
return file
def run_validators(self, value: str):
if not self.is_svg(value):
return super(ImageField, self).run_validators(value)
return super(SVGImageField, self).run_validators(value)
def is_svg(file):
"""Check if the provided file is a SVG image."""
file = if hasattr(file, 'seek') else open(file)
tag = '{}svg'
iter = et.iterparse(file, ('start',))
return next(iter)[1].tag == tag
except et.ParseError:
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment