Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

0.1

  • Loading branch information...
commit 59d0185ef860192ad4d963e6f3a17611fb04d5a1 1 parent 5d2f26b
@gustavodiazjaimes authored
View
0  django_pgarray/__init__.py
No changes.
View
76 django_pgarray/fields.py
@@ -0,0 +1,76 @@
+# -*- coding: utf-8 -*-
+
+from django.db import models
+from django.core import exceptions, validators
+from django.utils.translation import ugettext_lazy as
+
+from forms import PgArrayFormField
+
+
+class PgArrayField(models.Field):
+ default_error_messages = {
+ 'invalid': _(u"'%s' value must be array."),
+ }
+ description = _("Array")
+
+ __metaclass__ = models.SubfieldBase
+
+ def __init__(self, field, *args, **kwargs):
+ assert(isintance(field, models.Field))
+ self._field = field(*args, **kwargs)
+ kwargs.setdefault('blank', True)
+ kwargs.setdefault('null', True)
+ kwargs.setdefault('default', None)
+ super(PgArrayField, self).__init__(*args, **kwargs)
+
+ def db_type(self, connection):
+ return '%s[]' % self._field.db_type(connection)
+
+ def to_python(self, value):
+ field = self._field
+ if value in validators.EMPTY_VALUES:
+ return []
+ if isinstance(value, (list,tuple)):
+ return map(field.to_python, value)
+ return value
+
+ def get_prep_value(self, value):
+ field = self._field
+ return [field.get_prep_value(v) for v in value]
+
+ def get_db_prep_value(self, value, connection, prepared=False):
+ field = self._field
+ value = value if prepared else self.get_prep_value(value)
+
+ if not value:
+ return value
+ value = [field.get_db_prep_value(v, connection, True) for v in value]
+ return value
+
+ def get_prep_lookup(self, lookup_type, value):
+ """
+ Perform preliminary non-db specific lookup checks and conversions
+ """
+ if value:
+ if hasattr(value[0], 'prepare'):
+ return [v.prepare() for v in values]
+ if hasattr(value[0], '_prepare'):
+ return [v._prepare() for v in values]
+
+ return self.get_prep_value(value)
+
+ def formfield(self, *args, **kwargs):
+ defaults = {'form_class':PgArrayFormField()}
+ defaults.update(kwargs)
+ return super(PgArrayField, self).formfield(*args, **defaults)
+
+ def value_to_string(self, obj):
+ value = self._get_val_from_obj(obj)
+ return unicode(value)
+
+
+try:
+ from south.modelsinspector import add_introspection_rules
+ add_introspection_rules([], ['django_postgres_array\.fields\.PgArrayField'])
+except ImportError:
+ pass
View
66 django_pgarray/forms.py
@@ -0,0 +1,66 @@
+# -*- coding: utf-8 -*-
+
+from django import forms
+from django.utils.translation import ugettext_lazy as _
+
+import datetime
+from collections import defaultdict
+
+from utils import parselist, parsestring
+
+class PgArrayWidget(forms.TextInput):
+ def render(self, name, value, attrs=None):
+ if value is not None:
+ value = parselist(value)
+ return super(PgArrayWidget, self).render(name, value, attrs)
+
+def PgArrayFormField(formfield):
+ class FieldArray(forms.CharField):
+
+ widget = PgArrayWidget
+
+ def to_python(self, value):
+ if not value:
+ return None
+ return [formfield.to_python(v) for v in value]
+
+ def clean(self, value):
+ value = super(TagField, self).clean(value)
+ try:
+ return parse_tags(value)
+ except ValueError:
+ raise forms.ValidationError(_("Please provide a comma-separated list of tags."))
+
+
+
+
+
+class PgArrayFormField(forms):
+ #default_error_messages = {
+ # 'invalid':_('Enter a valid time span: e.g. "3 days, 4 hours, 2 minutes"')
+ #}
+
+ def __init__(self, *args, **kwargs):
+ defaults = {'widget':TimedeltaWidget}
+ defaults.update(kwargs)
+ super(PgArrayFormField, self).__init__(*args, **defaults)
+
+ def clean(self, value):
+ super(PgArrayFormField, self).clean(value)
+ if value == '' and not self.required:
+ return u''
+
+ data = defaultdict(float)
+ try:
+ return parse(value)
+ except TypeError:
+ raise forms.ValidationError(self.error_messages['invalid'])
+
+ return datetime.timedelta(**data)
+
+#class PgArrayChoicesField(TimedeltaFormField):
+# def __init__(self, *args, **kwargs):
+# choices = kwargs.pop('choices')
+# defaults = {'widget':forms.Select(choices=choices)}
+# defaults.update(kwargs)
+# super(TimedeltaChoicesField, self).__init__(*args, **defaults)
View
3  django_pgarray/models.py
@@ -0,0 +1,3 @@
+from django.db import models
+
+# Create your models here.
View
16 django_pgarray/tests.py
@@ -0,0 +1,16 @@
+"""
+This file demonstrates writing tests using the unittest module. These will pass
+when you run "manage.py test".
+
+Replace this with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+
+class SimpleTest(TestCase):
+ def test_basic_addition(self):
+ """
+ Tests that 1 + 1 always equals 2.
+ """
+ self.assertEqual(1 + 1, 2)
View
21 django_pgarray/utils.py
@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+
+from StringIO import StringIO
+import unicodecsv as csv
+
+
+class pgarray_dialect(csv.csv.excel):
+ skipinitialspace = True
+ lineterminator = ''
+
+
+def parselist(value):
+ f = StringIO()
+ w = csv.writer(f, pgarray_dialect)
+ w.writerow(value)
+ f.seek(0)
+ return f.read()
+
+def parsestring(value):
+ f = StringIO(value)
+ return csv.reader(f, pgarray_dialect).next()
View
43 django_pgarray/widgets.py
@@ -0,0 +1,43 @@
+from django import forms
+
+
+class PgArrayWidget(forms.MultiWidget):
+ def __init__(self, field, attrs=None):
+
+ widgets = (DateInput(attrs=attrs, format=date_format),
+ TimeInput(attrs=attrs, format=time_format))
+ super(SplitDateTimeWidget, self).__init__(widgets, attrs)
+
+ def __init__(self, *args, **kwargs):
+ return super(PgArrayWidget, self).__init__(*args, **kwargs)
+
+ def render(self, name, value, attrs):
+ if value is None:
+ value = ""
+ elif isinstance(value, (str, unicode)):
+ pass
+ else:
+ if isinstance(value, int):
+ value = datetime.timedelta(seconds=value)
+ value = nice_repr(value)
+ return super(TimedeltaWidget, self).render(name, value, attrs)
+
+ def _has_changed(self, initial, data):
+ """
+ We need to make sure the objects are of the canonical form, as a
+ string comparison may needlessly fail.
+ """
+ if initial in ["", None] and data in ["", None]:
+ return False
+
+ if initial in ["", None] or data in ["", None]:
+ return True
+
+ if initial:
+ if not isinstance(initial, datetime.timedelta):
+ initial = parse(initial)
+
+ if not isinstance(data, datetime.timedelta):
+ data = parse(data)
+
+ return initial != data
View
2  requirements.txt
@@ -0,0 +1,2 @@
+#python-unicodecsv
+-e git+git://github.com/jdunck/python-unicodecsv.git#egg=python-unicodecsv
Please sign in to comment.
Something went wrong with that request. Please try again.