HTML Hex Color Field

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import re
from django.forms import fields
from django.forms import ValidationError
from django.utils.encoding import smart_unicode

class HexColorField(fields.Field):
    
    default_error_messages = {
        'hex_error': u'This is an invalid color code. It must be a html hex color code e.g. #000000'
    }

    def clean(self, value):
        
        super(HexColorField, self).clean(value)
        
        if value in fields.EMPTY_VALUES:
            return u''
        
        value = smart_unicode(value)
        value_length = len(value)
        
        if value_length != 7 or not re.match('^\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$', value):
            raise ValidationError(self.error_messages['hex_error'])
        
        return value

    def widget_attrs(self, widget):
        if isinstance(widget, (fields.TextInput)):
            return {'maxlength': str(7)}

More like this

  1. HTML color code field by b23 5 years, 9 months ago
  2. Custom color field with Javascript color picker by seanl 5 years, 9 months ago
  3. models ColorField with clean minimal widget by andybak 2 years, 11 months ago
  4. A Django form field that accepts an uploaded image and creates a resized image attached with a push-pin by rmisio 2 years, 10 months ago
  5. Django template tag to hash/map a value to a unique web color. by danielsokolowski 2 years, 5 months ago

Comments

ursomniac (on February 12, 2013):

This doesn't seem to work with South. Trying to migrate the model using it throws an error:

TypeError: init() got an unexpected keyword argument 'null'

Any suggestions?

#

(Forgotten your password?)