Login

HTML Hex Color Field

Author:
claudelacey
Posted:
May 23, 2009
Language:
Python
Version:
1.0
Tags:
fields forms color hex
Score:
2 (after 2 ratings)

A custom form field than validates html hex color fields

 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 6 years, 8 months ago
  2. Custom color field with Javascript color picker by seanl 6 years, 8 months ago
  3. models ColorField with clean minimal widget by andybak 3 years, 10 months ago
  4. A Django form field that accepts an uploaded image and creates a resized image attached with a push-pin by rmisio 3 years, 10 months ago
  5. Django template tag to hash/map a value to a unique web color. by danielsokolowski 3 years, 4 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?

#

ilanouh (on October 6, 2014):

I know it's been more than a year, but I think that when you have this error with South, you need to declare your field with a "max_length=255". I used it for another Field and it worked. For example :

languages = MultiSelectField(choices=settings.LANGUAGES, max_length=255)

Hope this can help someone.

#

Please login first before commenting.