Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
- Loading branch information
Showing
3 changed files
with
52 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
# 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}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters