6

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.

resueman
  • 10,572
  • 10
  • 31
  • 45
m4tx
  • 4,139
  • 5
  • 37
  • 61

1 Answers1

6

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...

Jerzyk
  • 3,662
  • 23
  • 40