Login

HTML color code field

Author:
b23
Posted:
July 9, 2008
Language:
Python
Version:
.96
Tags:
model db color hexcode
Score:
1 (after 1 ratings)

A CharField (Model) that checks that the value is a valid HTML color code (Hex triplet) like #FFEE00.

 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
30
31
32
33
from django.db import models
from django.core import validators

class HtmlColorCodeField(models.CharField):
    """
    A CharField that checks that the value is a valid HTML color code (Hex triplet).
    Has no required argument.
    
    """
    def __init__(self, **kwargs):
        kwargs['max_length'] = 7
        validator_list = kwargs.get('validator_list', [])
        validator_list.append(HtmlColorCodeField.is_html_color_code)
        kwargs['validator_list'] = validator_list
        super(HtmlColorCodeField,self).__init__(**kwargs)
        
    def get_internal_type(self):
        return "CharField"
    
    @staticmethod    
    def is_html_color_code(field_data, all_data):
        """
        Checks that field_data is a HTML color code string.
        
        """
        try:
            if not field_data.startswith("#") or not field_data[1:].isalnum() or not len(field_data) == 7:
                raise validators.ValidationError("Please enter a valid HTML color.")
        except (TypeError, ValueError), e:
            raise validators.ValidationError, str(e)
    
    def validate(self, value, all_values):
        HtmlColorCodeField.is_html_color_code(value, all_values)

More like this

  1. HTML Hex Color Field by claudelacey 6 years, 1 month ago
  2. Django template tag to hash/map a value to a unique web color. by danielsokolowski 3 years, 7 months ago
  3. jQuery color picker model field by fneumann 6 years, 6 months ago
  4. Colorize Filter by empty 7 years, 4 months ago
  5. models ColorField with clean minimal widget by andybak 4 years, 1 month ago

Comments

Please login first before commenting.