datatracker/ietf/utils/db.py
Mark J. Donnelly 604d6edef0 Add a new Django field, IETFJSONField
This field is needed because the plain JSONField does not permit empty arrays - [] - or empty objects - {} - when the field is marked as required.  Those values explicitly evaluate to a null value, and are rejected.

Instead, the IETFJSONField accepts two new arguments to control this:
- empty_values: An array of values that should evaluate to null/empty, and be rejected.
- accepted_empty_values: An array of values that should *not* evaluate to null/empty, and be accepted.

This allows the programmer to specify either a positive or negative statement of what values to accept.

Fixes issue #3331.  Commit ready for merge.
 - Legacy-Id: 19401
2021-10-07 19:30:51 +00:00

29 lines
1.1 KiB
Python

# Copyright The IETF Trust 2021, All Rights Reserved
# -*- coding: utf-8 -*-
# Taken from/inspired by
# https://stackoverflow.com/questions/55147169/django-admin-jsonfield-default-empty-dict-wont-save-in-admin
#
# JSONField should recognize {}, (), and [] as valid, non-empty JSON
# values. However, the base Field class excludes them
import jsonfield
from ietf.utils.fields import IETFJSONField as FormIETFJSONField
class IETFJSONField(jsonfield.JSONField):
form_class = FormIETFJSONField
def __init__(self, *args, empty_values=FormIETFJSONField.empty_values, accepted_empty_values=None, **kwargs):
if accepted_empty_values is None:
accepted_empty_values = []
self.empty_values = [x
for x in empty_values
if x not in accepted_empty_values]
super().__init__(*args, **kwargs)
def formfield(self, **kwargs):
if issubclass(kwargs['form_class'], FormIETFJSONField):
kwargs.setdefault('empty_values', self.empty_values)
return super().formfield(**{**kwargs})