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
- Add Toggle Switch Widget to Django Forms by OgliariNatan 1 month, 3 weeks ago
- get_object_or_none by azwdevops 5 months, 2 weeks ago
- Mask sensitive data from logger by agusmakmun 7 months, 1 week ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 9 months ago
Comments
Please login first before commenting.