1 # -*- coding: utf-8 -*-
4 from django.conf import settings
5 from django.db import models
6 from django.db.models import signals
7 from django.dispatch import dispatcher
8 from django import forms
9 from django.forms.widgets import flatatt
10 from django.forms.util import smart_unicode
11 from django.utils import simplejson as json
12 from django.utils.html import escape
13 from django.utils.safestring import mark_safe
16 class JSONEncoder(json.JSONEncoder):
17 def default(self, obj):
18 if isinstance(obj, datetime.datetime):
19 return obj.strftime('%Y-%m-%d %H:%M:%S')
20 elif isinstance(obj, datetime.date):
21 return obj.strftime('%Y-%m-%d')
22 elif isinstance(obj, datetime.time):
23 return obj.strftime('%H:%M:%S')
24 return json.JSONEncoder.default(self, obj)
28 return JSONEncoder().encode(data)
32 return json.loads(str, encoding=settings.DEFAULT_CHARSET)
35 class JSONField(models.TextField):
39 def get_internal_type(self):
42 def pre_save(self, model_instance, add):
43 value = getattr(model_instance, self.attname, None)
46 def contribute_to_class(self, cls, name):
47 super(JSONField, self).contribute_to_class(cls, name)
48 dispatcher.connect(self.post_init, signal=signals.post_init, sender=cls)
50 def get_json(model_instance):
51 return dumps(getattr(model_instance, self.attname, None))
52 setattr(cls, 'get_%s_json' % self.name, get_json)
54 def set_json(model_instance, json):
55 return setattr(model_instance, self.attname, loads(json))
56 setattr(cls, 'set_%s_json' % self.name, set_json)
58 def post_init(self, instance=None):
59 value = self.value_from_object(instance)
61 setattr(instance, self.attname, loads(value))
63 setattr(instance, self.attname, None)
66 class JQueryAutoCompleteWidget(forms.TextInput):
67 def __init__(self, source, options=None, *args, **kwargs):
71 self.options = dumps(options)
72 super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
74 def render_js(self, field_id):
75 source = "'%s'" % escape(self.source)
78 options += ', %s' % self.options
80 return u'$(\'#%s\').autocomplete(%s%s);' % (field_id, source, options)
82 def render(self, name, value=None, attrs=None):
83 final_attrs = self.build_attrs(attrs, name=name)
85 final_attrs['value'] = smart_unicode(value)
87 if not self.attrs.has_key('id'):
88 final_attrs['id'] = 'id_%s' % name
90 html = u'''<input type="text" %(attrs)s/>
91 <script type="text/javascript">//<!--
94 'attrs' : flatatt(final_attrs),
95 'js' : self.render_js(final_attrs['id']),
98 return mark_safe(html)
101 class JQueryAutoCompleteField(forms.CharField):
102 def __init__(self, source, options=None, *args, **kwargs):
103 if 'widget' not in kwargs:
104 kwargs['widget'] = JQueryAutoCompleteWidget(source, options)
106 super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)