forked from ietf-tools/datatracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
67 lines (54 loc) · 2.17 KB
/
db.py
File metadata and controls
67 lines (54 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Copyright The IETF Trust 2021-2025, All Rights Reserved
import jsonfield
from django.db import models
from ietf.utils.fields import (
IETFJSONField as FormIETFJSONField,
EmptyAwareJSONField as FormEmptyAwareJSONField,
)
class EmptyAwareJSONField(models.JSONField):
"""JSONField that allows empty JSON values when model specifies empty=False
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.
If customizing the formfield, the field must accept the `empty_values` argument.
"""
def __init__(
self,
*args,
empty_values=FormEmptyAwareJSONField.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):
defaults = {
"form_class": FormEmptyAwareJSONField,
"empty_values": self.empty_values,
}
defaults.update(kwargs)
return super().formfield(**defaults)
class IETFJSONField(jsonfield.JSONField): # pragma: no cover
# Deprecated - use EmptyAwareJSONField instead (different base class requires a
# new field name)
# Remove this class when migrations are squashed and it is no longer referenced
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 "form_class" not in kwargs or issubclass(
kwargs["form_class"], FormIETFJSONField
):
kwargs.setdefault("empty_values", self.empty_values)
return super().formfield(**{**kwargs})