- Author:
- claudelacey
- Posted:
- May 23, 2009
- Language:
- Python
- Version:
- 1.0
- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
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?
#
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.