forked from apluslms/a-plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fields.py
89 lines (73 loc) · 2.4 KB
/
fields.py
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import json
from django import forms
from django.core import exceptions
from django.db import models
from django.utils.translation import ugettext_lazy as _
try:
# If South is used, it requires additional rules for processing
# custom fields. In this case we add empty inspection rules for the
# percent field.
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^lib\.fields\.PercentField"])
except:
pass
class PercentField(models.FloatField):
"""
A float in range 0.0 to 1.0
"""
def clean(self, value, model_instance):
value = super(PercentField, self).clean(value, model_instance)
if value and (value < 0.0 or value > 1.0):
raise exceptions.ValidationError(
_("The number must be between 0.0 and 1.0")
)
return value
class JSONField(models.TextField):
"""
Stores JSON object in a text field.
"""
def __init__(self, *args, **kwargs):
super(JSONField, self).__init__(*args, **kwargs)
@classmethod
def parse_json(cls, value):
if not value:
return None
if isinstance(value, str):
try:
return json.loads(value)
except (TypeError, ValueError):
raise exceptions.ValidationError(_("Enter valid JSON."))
return value
@classmethod
def print_json(cls, value):
if not value:
return ""
if isinstance(value, str):
return value
return json.dumps(value)
def from_db_value(self, value, expression, connection):
try:
return JSONField.parse_json(value)
except (exceptions.ValidationError):
return None
def get_prep_value(self, value):
return JSONField.print_json(value)
def to_python(self, value):
return JSONField.parse_json(value)
def formfield(self, **kwargs):
defaults = {
'form_class': JSONFormField,
}
defaults.update(kwargs)
field = super(JSONField, self).formfield(**defaults)
if not field.help_text:
field.help_text = _("Enter valid JSON.")
return field
class JSONFormField(forms.CharField):
"""
A JSON text area.
"""
def to_python(self, value):
return JSONField.parse_json(value)
def prepare_value(self, value):
return JSONField.print_json(value)