<s> from __future__ import absolute_import , unicode_literals <EOL> import json <EOL> import logging <EOL> from django import forms <EOL> from django . db import models <EOL> from django . core . serializers . json import DjangoJSONEncoder <EOL> from django . utils import six <EOL> class JSONFormField ( forms . fields . CharField ) : <EOL> def clean ( self , value , * args , ** kwargs ) : <EOL> if value : <EOL> if isinstance ( value , six . string_types ) : <EOL> try : <EOL> value = json . loads ( value ) <EOL> except ValueError : <EOL> raise forms . ValidationError ( "<STR_LIT>" ) <EOL> try : <EOL> value = json . dumps ( value , cls = DjangoJSONEncoder ) <EOL> except ValueError : <EOL> raise forms . ValidationError ( "<STR_LIT>" ) <EOL> return super ( JSONFormField , self ) . clean ( value , * args , ** kwargs ) <EOL> class JSONField ( six . with_metaclass ( models . SubfieldBase , models . TextField ) ) : <EOL> """<STR_LIT>""" <EOL> formfield = JSONFormField <EOL> def to_python ( self , value ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( value , dict ) : <EOL> return value <EOL> elif ( isinstance ( value , six . string_types ) <EOL> or isinstance ( value , six . binary_type ) ) : <EOL> if not value : <EOL> return { } <EOL> try : <EOL> return json . loads ( value ) <EOL> except ValueError : <EOL> logging . getLogger ( "<STR_LIT>" ) . exception ( <EOL> "<STR_LIT>" , value ) <EOL> return { } <EOL> else : <EOL> assert value is None <EOL> return { } <EOL> def get_prep_value ( self , value ) : <EOL> """<STR_LIT>""" <EOL> return self . _flatten_value ( value ) <EOL> def value_to_string ( self , obj ) : <EOL> """<STR_LIT>""" <EOL> if hasattr ( obj , self . attname ) : <EOL> value = getattr ( obj , self . attname ) <EOL> else : <EOL> assert isinstance ( obj , dict ) <EOL> value = obj . get ( self . attname , "<STR_LIT>" ) <EOL> return self . _flatten_value ( value ) <EOL> def _flatten_value ( self , value ) : <EOL> """<STR_LIT>""" <EOL> if not value : <EOL> return "<STR_LIT>" <EOL> if isinstance ( value , dict ) : <EOL> value = json . dumps ( value , cls = DjangoJSONEncoder ) <EOL> assert isinstance ( value , six . string_types ) <EOL> return value <EOL> try : <EOL> from south . modelsinspector import add_introspection_rules <EOL> JSONField_introspection_rule = ( ( JSONField , ) , [ ] , { } , ) <EOL> add_introspection_rules ( <EOL> rules = [ JSONField_introspection_rule ] , <EOL> patterns = [ "<STR_LIT>" ] ) <EOL> except ImportError : <EOL> pass </s>
