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:
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
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
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?"
As you can see, it’s a slightly modified version of
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.
To be able to upload/use svg images with Django Rest Framework you shoud perform next steps:
Switch your model’s ImageField to the FileField (don’t forget to migrate!).
Grab the gist and put it somewhere in your project.
Import SVGAndImageFormField to the file with your serializers from the gist file. Import
ImageField from rest_framework.fields.
Update validation in your serializers:
image = ImageField(required=False, _DjangoImageField=SVGAndImageFormField)