File: forms.py

package info (click to toggle)
python-django-jsonfield 1.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 204 kB
  • sloc: python: 568; makefile: 6
file content (31 lines) | stat: -rw-r--r-- 921 bytes parent folder | download
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
import json

from django import forms
import six

from .widgets import JSONWidget


class JSONFormField(forms.CharField):
    empty_values = [None, '']

    def __init__(self, *args, **kwargs):
        if 'widget' not in kwargs:
            kwargs['widget'] = JSONWidget
        super(JSONFormField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if isinstance(value, six.string_types) and value:
            try:
                return json.loads(value)
            except ValueError as exc:
                raise forms.ValidationError(
                    'JSON decode error: %s' % (six.u(exc.args[0]),)
                )
        else:
            return value

    def validate(self, value):
        # This is required in older django versions.
        if value in self.empty_values and self.required:
            raise forms.ValidationError(self.error_messages['required'], code='required')