Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A form field to handle validation of image + svg in Django 3
import sys
import xml.etree.cElementTree as et
from io import BytesIO
from django.core.exceptions import ValidationError
from django.core.validators import (
from django.forms import ImageField as DjangoImageField
from PIL import Image
def validate_image_and_svg_file_extension(value):
allowed_extensions = get_available_image_extensions() + ["svg"]
return FileExtensionValidator(allowed_extensions=allowed_extensions)(value)
class SVGAndImageFormField(DjangoImageField):
default_validators = [validate_image_and_svg_file_extension]
def to_python(self, data):
Checks that the file-upload field data contains a valid image (GIF, JPG,
PNG, possibly others -- whatever the Python Imaging Library supports).
test_file = super(DjangoImageField, self).to_python(data)
if test_file is None:
return None
# We need to get a file object for Pillow. We might have a path or we might
# have to read the data into memory.
if hasattr(data, "temporary_file_path"):
ifile = data.temporary_file_path()
if hasattr(data, "read"):
ifile = BytesIO(
ifile = BytesIO(data["content"])
# load() could spot a truncated JPEG, but it loads the entire
# image in memory, which is a DoS vector. See #3848 and #18520.
image =
# verify() must be called immediately after the constructor.
# Annotating so subclasses can reuse it for their own validation
test_file.image = image
test_file.content_type = Image.MIME[image.format]
except Exception:
# add a workaround to handle svg images
if not self.is_svg(ifile):
raise ValidationError(
self.error_messages["invalid_image"], code="invalid_image",
if hasattr(test_file, "seek") and callable(
return test_file
def is_svg(self, f):
Check if provided file is svg
tag = None
for event, el in et.iterparse(f, ("start",)):
tag = el.tag
except et.ParseError:
return tag == "{}svg"

This comment has been minimized.

Copy link
Owner Author

@ramsrib ramsrib commented Jun 22, 2020

Example usage:

from django.db import models
from rest_framework import serializers

class Image(models.Model):
    image = models.ImageField()

class ImageSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(_DjangoImageField=SVGAndImageFormField)

    class Meta:
        model = Image
        fields = "__all__"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment