Django-rest-braces (drf-braces) is all about adding useful utilities for working with DRF. This overview will go over some of the most useful ones. You can refer to the API docs or source code to see documentation about all of the utilities.
Many Django applications are built using standard Django practices following basic request-response
data flow. Safe way of dealing with user-input in such applications is to use
Django forms. That works really well until application needs to be extended to introduce services
since many of the forms might need to be rewritten (as serializers when using DRF).
That situation becomes much worse custom forms (not
ModelForm) need to be migrated.
Same issue presents itself when Django application is initially started by using services but later needs to add basic UI using Django forms.
DRF-braces attempts to solve these challenges by providing converters to go from form to
serializer and vise-versa -
FormSerializer is a special
serializer class which converts existing
Serializer while preserving form validation logic.
It works very similar to
from django import forms from drf_braces.serializers.form_serializer import FormSerializer class MyForm(forms.Form): foo = forms.CharField(max_length=32) bar = forms.DateTimeField() class MySerializer(FormSerializer): class Meta(object): form = MyForm
SerializerForm is a special form class
which converts existing
Form while preserving serializer validation logic.
It works very similar to
from rest_framework import serializers from drf_braces.forms.serializer_form import SerializerForm class MySerializer(serializers.Serializer): foo = serializers.CharField(max_length=32) bar = serializers.DateTimeField() class MyForm(SerializerForm): class Meta(object): serializer = MySerializer
SerializerForm does not support nested serializers.
DRF has a concept of partial serializers which then only validate data supplied in request payload. The problem is that if the data is sent, it must be valid and if a single field is invalid, the whole serializer validation fails and error is returned to the consumer. That however is not always desired if the application must accept the payload as is and ignore invalid data.
which returns a recursive serializer copy does just that. It only enforces validation on specified
fields and if validation fails on non-specified fields, it ignores that data:
from rest_framework import serializers from drf_braces.serializers import enforce_validation_serializer class MySerializer(serializers.Serializer): must_validate_fields = ['foo'] foo = serializers.CharField(max_length=32) bar = serializers.DateTimeField() MyEnforceValidationSerializer = enforce_validation_serializer(MySerializer)
Even though above
still enforces validation on all fields. Only serializers returned by
must_validate_fields in field validation.