Skip to main content

DRF NESTED FORMS

A library that parses nested json or form data to python object.

Build Status GitHub release (latest by date) PyPI - License PyPI - Python Version PyPI - Django Version PyPI

Overview

SPA's, sometimes send nested form data or json as requests encoded by some javascript libraries like json-form-data which can be difficult to handle due to the key naming conventions. This library helps to eliminate that difficulty, by parsing that nested requests into a more predictable python object that can be used by libraries like drf_writable_nested or used directly in the code.

Installation

It is available via pypi:

pip install drf_nested_forms

Usage

The utiliy class can be used directly in any part of the code.

from drf_nested_forms.utils import NestedForm

data = {
    'item[attribute][0][user_type]': 'size',
    'item[attribute][1][user_type]': '',
    'item[verbose][]': '',
    'item[variant][vendor_metric]': '[]',
    'item[variant][metric_verbose_name]': 'Large',
    'item[foo][baaz]': 'null',
}

options = {
    'allow_blank': True,
    'allow_empty': False
}

Note

.is_nested() should be called before accessing the .data

form = NestedForm(data, **options)
form.is_nested(raise_exception=True)

The parsed result will look like below:

print(form.data)

data = {
    'item': {
        'attribute': [
            {'user_type': 'size'},
            {'user_type': ''}
        ],
        'verbose': [''],
        'variant': {
            'vendor_metric': None,
            'metric_verbose_name': 'Large'
        },
        'foo': { 'baaz': None }
    }
}

DRF Integration

The parser is used with a djangorestframework view classes.

Parser classes supported:

  • NestedMultiPartParser: is a default DRF multipart parser that suppport parsing nested form data.
  • NestedJSONParser: is a default DRF JSONParser that support parsing nested json request.

Add the parser to your django settings file

#...

REST_FRAMEWORK = {
    DEFAULT_PARSER_CLASSES = [
        # nested parser are just default DRF parsers with extended
        # functionalities to support nested

        'drf_nested_forms.parsers.NestedMultiPartParser',
        'drf_nested_forms.parsers.NestedJSONPartParser',
        'rest_framework.parsers.FormParser',

        # so this settings will work in respective of a nested request
        # or not
    ]
}

#...

To change default settings of the parsers, add OPTIONS to NESTED_FORM_PARSER with the new settings to your django settings file

#..

NESTED_FORM_PARSER = {
    'OPTIONS': {
        'allow_empty': False,
        'allow_blank': True
    }
}

#...

The parsers can also be used directly in a rest_framework view class

from rest_framework.views import APIView
from rest_framework.parsers import FormParser
from rest_framework.response import Response

from drf_nested_forms.parsers import NestedMultiPartParser, NestedJSONParser

class TestMultiPartParserView(APIView):
    parser_classes = (NestedMultiPartParser, FormParser)

    def post(self, request):
        return Response(data=request.data, status=200)

# or

class TestJSONParserView(APIView):
    parser_classes = (NestedJSONParser, FormParser)

    def post(self, request):
        return Response(data=request.data, status=200)

For example, a form or JSON data with nested params like below can be posted to any of the above drf view:

data = {
    '[0][attribute]': 'true',
    '[0][verbose][0]': 'bazz',
    '[0][verbose][1]': 'foo',
    '[0][variant][vendor_metric]': 'null',
    '[0][variant][metric_verbose_name]': 'Large',
    '[0][foo][baaz]': 'false',
    '[1][attribute]': 'size',
    '[1][verbose]': '[]',
    '[1][variant][vendor_metric]': '{}',
    '[1][variant][metric_verbose_name][foo][baaz][]': 'Large',
    '[1][foo][baaz]': '',
    '[1][logo]': '235'
}

after being parsed, the request.data will look like this:

print(request.data)

data = [
    {
        'attribute': True,
        'verbose': ['bazz', 'foo'],
        'variant': {
            'vendor_metric': None,
            'metric_verbose_name': 'Large'
        },
        'foo': { 'baaz': False }
    },
    {
        'attribute': 'size',
        'verbose': None,
        'variant': {
            'vendor_metric': None,
            'metric_verbose_name': { 'foo': { 'baaz': ['Large'] } }
        },
        'foo': { 'baaz': '' },
        'logo': 235
    }
]

Options

Option Default Description
allow_blank True shows empty string '' in the object
allow_empty False shows empty list or dict object

Running Tests

To run the current test suite, execute the following from the root of the project:

python runtests.py

Author

@Copyright 2021, Duke Effiom

Metadata

Release files for drf-nested-forms 1.1.8

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for drf-nested-forms 1.1.8
File Size Uploaded Provenance Actions
drf_nested_forms-1.1.8.tar.gz 12.9 kB Without provenance Details for drf_nested_forms-1.1.8.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for drf-nested-forms 1.1.8
File Interpreter ABI Platform Actions
drf_nested_forms-1.1.8-py3-none-any.whl Python 3 none any Details for drf_nested_forms-1.1.8-py3-none-any.whl

Total release size: 23.0 kB

Release files / drf_nested_forms-1.1.8.tar.gz

Download URL drf_nested_forms-1.1.8.tar.gz
Size 12.9 kB
Tags Source
SHA-256 checksum
How to use checksums
5d086b7e68c56915f430bd5a1beffe0c79a6ac48424732287d056c5322e65f93
BLAKE2b-256 checksum
How to use checksums
c6aeef5de4614e0f1ec8941890990cec54e580665a4382b43a2da77a1d0ab535
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.1 importlib_metadata/4.5.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.0 CPython/3.11.5

Release files / drf_nested_forms-1.1.8-py3-none-any.whl

Download URL drf_nested_forms-1.1.8-py3-none-any.whl
Size 10.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
087fe5b6df32c95fcc605962a61109df08e7059580ef3adc6ba9de68d375b57b
BLAKE2b-256 checksum
How to use checksums
fc7e339ba9cf19f02202538ad51619855b48ab9d0e6d066c89641cad976e71b1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.1 importlib_metadata/4.5.0 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.61.0 CPython/3.11.5

Security for drf-nested-forms 1.1.8

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page