Login

HTML color code field

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

Comments

Please login first before commenting.