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 import forms
8 from django.forms.widgets import flatatt
9 from django.forms.util import smart_unicode
10 from django.utils import simplejson as json
11 from django.utils.html import escape
12 from django.utils.safestring import mark_safe
15 class JSONEncoder(json.JSONEncoder):
16 def default(self, obj):
17 if isinstance(obj, datetime.datetime):
18 return obj.strftime('%Y-%m-%d %H:%M:%S')
19 elif isinstance(obj, datetime.date):
20 return obj.strftime('%Y-%m-%d')
21 elif isinstance(obj, datetime.time):
22 return obj.strftime('%H:%M:%S')
23 return json.JSONEncoder.default(self, obj)
27 return JSONEncoder().encode(data)
31 return json.loads(str, encoding=settings.DEFAULT_CHARSET)
34 class JSONFormField(forms.CharField):
35 widget = forms.Textarea
37 def clean(self, value):
42 raise forms.ValidationError('Enter a valid JSON value. Error: %s' % e)
45 class JSONField(models.TextField):
46 def formfield(self, **kwargs):
47 defaults = {'form_class': JSONFormField}
48 defaults.update(kwargs)
49 return super(JSONField, self).formfield(**defaults)
54 def get_internal_type(self):
57 def contribute_to_class(self, cls, name):
58 super(JSONField, self).contribute_to_class(cls, name)
60 def get_value(model_instance):
61 return loads(getattr(model_instance, self.attname, None))
62 setattr(cls, 'get_%s_value' % self.name, get_value)
64 def set_value(model_instance, json):
65 return setattr(model_instance, self.attname, dumps(json))
66 setattr(cls, 'set_%s_value' % self.name, set_value)
69 class JQueryAutoCompleteWidget(forms.TextInput):
70 def __init__(self, source, options=None, *args, **kwargs):
74 self.options = dumps(options)
75 super(JQueryAutoCompleteWidget, self).__init__(*args, **kwargs)
77 def render_js(self, field_id):
78 source = "'%s'" % escape(self.source)
81 options += ', %s' % self.options
83 return u'$(\'#%s\').autocomplete(%s%s);' % (field_id, source, options)
85 def render(self, name, value=None, attrs=None):
86 final_attrs = self.build_attrs(attrs, name=name)
88 final_attrs['value'] = smart_unicode(value)
90 if not self.attrs.has_key('id'):
91 final_attrs['id'] = 'id_%s' % name
93 html = u'''<input type="text" %(attrs)s/>
94 <script type="text/javascript">//<!--
97 'attrs' : flatatt(final_attrs),
98 'js' : self.render_js(final_attrs['id']),
101 return mark_safe(html)
104 class JQueryAutoCompleteField(forms.CharField):
105 def __init__(self, source, options=None, *args, **kwargs):
106 if 'widget' not in kwargs:
107 kwargs['widget'] = JQueryAutoCompleteWidget(source, options)
109 super(JQueryAutoCompleteField, self).__init__(*args, **kwargs)