DRF Extra Fields

3.7.0 · active · verified Thu Apr 16

drf-extra-fields provides additional serializer fields for Django Rest Framework, extending its capabilities beyond the default offerings. It includes fields for handling base64 encoded files, image dimensions, and PostgreSQL range types, among others. The library is actively maintained with irregular minor releases, ensuring compatibility with recent Django and DRF versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a serializer using `Base64ImageField` and how to pass base64 encoded image data to it for validation. The `Base64ImageField` expects the base64 string without the 'data:image/...' prefix. Upon successful validation, the field returns a `SimpleUploadedFile` instance, mimicking a file upload from a standard HTML form.

import base64
from rest_framework import serializers
from drf_extra_fields.fields import Base64ImageField

# Example usage with a serializer
class MyImageSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100)
    image = Base64ImageField(required=True)

# Simulate a base64 encoded image for demonstration
# This is a 1x1 transparent GIF: data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==
# Stripping the 'data:image/gif;base64,' prefix for the field's input
tiny_gif_base64 = 'R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='

# Example usage:
data = {
    'name': 'My Awesome Image',
    'image': tiny_gif_base64 # The base64 string without the prefix
}

serializer = MyImageSerializer(data=data)
if serializer.is_valid(raise_exception=True):
    print("Serializer data is valid!")
    print(serializer.validated_data)
    # The 'image' field in validated_data will be an instance of SimpleUploadedFile
    uploaded_file = serializer.validated_data['image']
    print(f"Uploaded file name: {uploaded_file.name}")
    print(f"Uploaded file size: {uploaded_file.size} bytes")
else:
    print("Validation failed:")
    print(serializer.errors)

view raw JSON →