# -*- coding: utf-8 -*-
from django import forms
from django.forms import Widget
from django import utils
import copy
try:
import simplejson as json
except ImportError:
import json
class SplitJSONWidget(forms.Widget):
def __init__(self, attrs=None, newline='
\n', sep='__', debug=False):
self.newline = newline
self.separator = sep
self.debug = debug
Widget.__init__(self, attrs)
def _as_text_field(self, name, key, value, is_sub=False):
attrs = self.build_attrs(self.attrs, type='text',
name="%s%s%s" % (name, self.separator, key))
attrs['value'] = utils.encoding.force_unicode(value)
attrs['id'] = attrs.get('name', None)
return u"""
""" % (attrs['id'], key, forms.util.flatatt(attrs))
def _to_build(self, name, json_obj):
inputs = []
if isinstance(json_obj, list):
title = name.rpartition(self.separator)[2]
_l = ['%s:%s' % (title, self.newline)]
for key, value in enumerate(json_obj):
_l.append(self._to_build("%s%s%s" % (name,
self.separator, key), value))
inputs.extend([_l])
elif isinstance(json_obj, dict):
title = name.rpartition(self.separator)[2]
_l = ['%s:%s' % (title, self.newline)]
for key, value in json_obj.items():
_l.append(self._to_build("%s%s%s" % (name,
self.separator, key),
value))
inputs.extend([_l])
elif isinstance(json_obj, (basestring, int)):
name, _, key = name.rpartition(self.separator)
inputs.append(self._as_text_field(name, key, json_obj))
elif json_obj is None:
name, _, key = name.rpartition(self.separator)
inputs.append(self._as_text_field(name, key, ''))
return inputs
def _prepare_as_ul(self, l):
if l:
result = ''
for el in l:
if isinstance(el, list) and len(l) is 1:
result += '%s' % self._prepare_as_ul(el)
elif isinstance(el, list):
result += '