File: forms.py

package info (click to toggle)
python-django-jsonfield 0.9.12-1~bpo70%2B1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy-backports
  • size: 160 kB
  • sloc: python: 476; makefile: 3
file content (31 lines) | stat: -rw-r--r-- 939 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
from django.utils 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 Exception as exc:
                raise forms.ValidationError(
                    'JSON decode error: %s' % (unicode(exc),)
                )
        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')