I see there is project called djangorestframework-camel-case, which allows to use JavaScript-ish camelCase with underscore_cased fields in Django REST serializers. So, basically, I can send:
{
"camelCase": "foo"
}
And receive it with following Serializer:
class MySerializer(serializers.Serializer):
session_id = serializers.CharField()
Does something similar for POST data exist? So I can send camelCase=foo
via POST and receive it to an underscore_case field in my serializer?
I tried implementing my own parser based on FormParser:
class CamelCaseFormParser(FormParser):
media_type = 'application/x-www-form-urlencoded'
def __init__(self):
print("initialized")
def parse(self, stream, media_type=None, parser_context=None):
print("parse")
...
And, after adding it to DEFAULT_PARSER_CLASSES
in settings.py, while initialized
is actually printed, parse
is not. So it seems, in case of POST data, application/x-www-form-urlencoded
parser is not used at all.
Since Serializers are used like that:
Serializer(data=request.data)
I'm thinking about subclassing Serializer and modifying data
before it gets processed further, or even modifying it before creating a Serializer. But what I'm asking for is a more convenient way, working for all Serializers, without subclassing them.
why not sticking with parsers?
from djangorestframework_camel_case.util import underscoreize
from rest_framework import parsers
from django.conf import settings
from django.http import QueryDict
class CamelCaseFormParser(parsers.FormParser):
def parse(self, stream, media_type=None, parser_context=None):
parser_context = parser_context or {}
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
data = QueryDict(stream.read(), encoding=encoding)
return underscoreize(data)
simple, working and properly placed...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With