[01/11] fields: Add ColorField

Message ID 20180415225405.1354-2-stephen@that.guru
State New
Headers show
Series
  • Add labels support
Related show

Commit Message

Stephen Finucane April 15, 2018, 10:53 p.m.
This will allow us to store color codes cleanly in the database.

Signed-off-by: Stephen Finucane <stephen@that.guru>
---
 patchwork/fields.py | 27 +++++++++++++++++++++++++--
 patchwork/forms.py  | 27 +++++++++++++++++++++++++++
 2 files changed, 52 insertions(+), 2 deletions(-)

Patch

diff --git a/patchwork/fields.py b/patchwork/fields.py
index 502558be..35bb13d6 100644
--- a/patchwork/fields.py
+++ b/patchwork/fields.py
@@ -18,8 +18,6 @@ 
 # along with Patchwork; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
-from __future__ import absolute_import
-
 import hashlib
 
 from django.db import models
@@ -44,3 +42,28 @@  class HashField(models.CharField):
 
     def db_type(self, connection=None):
         return 'char(%d)' % self.n_bytes
+
+
+class ColorField(models.Field):
+
+    description = 'Hex color code'
+
+    def get_internal_type(self):
+        return "PositiveIntegerField"
+
+    def to_python(self, value):
+        if isinstance(value, six.string_types) or value is None:
+            return value
+        return '#%06x' % value
+
+    def from_db_value(self, value, *args, **kwargs):
+        return self.to_python(value)
+
+    def get_prep_value(self, value):
+        return int(value.lstrip('#'), 16)
+
+    def formfield(self, *args, **kwargs):
+        from patchwork import forms  # noqa
+
+        kwargs['form_class'] = forms.ColorField
+        return super(ColorField, self).formfield(*args, **kwargs)
diff --git a/patchwork/forms.py b/patchwork/forms.py
index 0dd11857..e8a4955e 100644
--- a/patchwork/forms.py
+++ b/patchwork/forms.py
@@ -17,6 +17,8 @@ 
 # along with Patchwork; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
+import re
+
 from django.contrib.auth.models import User
 from django import forms
 from django.db.models import Q
@@ -214,3 +216,28 @@  class MultiplePatchForm(forms.Form):
         if commit:
             instance.save()
         return instance
+
+
+class ColorField(forms.CharField):
+
+    widget = forms.TextInput
+    default_error_messages = {
+        'invalid': 'Enter a valid colour value: e.g. "#ff0022"',
+    }
+
+    def __init__(self, *args, **kwargs):
+        super(ColorField, self).__init__(*args, **kwargs)
+
+    def clean(self, value):
+        if not re.match('^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$', value):
+            raise forms.ValidationError(self.error_messages['invalid'])
+
+        value = int(value.lstrip('#'), 16)
+        super(ColorField, self).clean(value)
+
+        return value
+
+    def widget_attrs(self, widget):
+        attrs = super().widget_attrs(widget)
+        attrs['maxlength'] = 7
+        return attrs