As you all know, svg is quite popular nowadays as a a format to serve images. If you use it, you are able to scale images enormously, thanks to its vector nature.

Here's a schema of image upload logic with Django REST framework:

Image upload logic drf

Request comes to the DRF, next it's validated via django.forms.ImageField (which will not validate svg in the nearest future), next data is pushed to the DB via models.ImageField.

How to make SVG files valid at the form field level

If you look at the to_internal_value method of DRF's ImageField, you'll see that all validation occurs when

django_field.to_python(file_object)

is called.

As you can see here, there's an option to provide another validator as an argument when you define Serializer:

class SomeSerializer(serializers.ModelSerializer):
    image = ImageField(required=False, _DjangoImageField=SVGAndImageFormField)

and voilà - you can pass validation with svg files.
Probably, you're guessing "oh, where can I get SVGAndImageFormField?"

HERE.

As you can see, it’s a slightly modified version of django.forms.ImageField.

Workaround for ORM layer

But one more issue is still there - you're not able to put svg file into models.ImageField because of dimensions that don't exist in svg file - it can be scaled to any size.
As a workaround, I've just switched from models.ImageField to the models.FileField in django models.

TL;DR

To be able to upload/use svg images with Django Rest Framework you shoud perform next steps:

  1. Switch your model’s ImageField to the FileField (don’t forget to migrate!).

  2. Grab the gist and put it somewhere in your project.

  3. Import SVGAndImageFormField to the file with your serializers from the gist file. Import
    ImageField from rest_framework.fields.

  4. Update validation in your serializers:

    image = ImageField(required=False, _DjangoImageField=SVGAndImageFormField)
    
  5. PROFIT!

2016-02-26