django-colour-field / colour_field / fields.py

from django.db import models
from forms import ColourFormField
import re

class ColourField(models.Field):
    """
    Store a colour as a CSS value (ie, #012345)
    
    We don't subclass models.CharField, as then the django admin would use
    it's AdminCharWidget or whatever, and we want to use our own.
    """
    
    __metaclass__ = models.SubfieldBase
    _south_introspects = True
    
    description = "A colour object"
    
    def to_python(self, value):
        # assert value[0] == "#" 
        # assert re.match('#[0-9a-fA-F]{6}', value)
        return value
    
    def get_prep_value(self, value):
        if not value.strip() and self.null:
            return None
        return value
    
    def value_to_string(self, value):
        return value.strip() or None
        
    def formfield(self, *args, **kwargs):
        defaults = {'form_class': ColourFormField}
        defaults.update(kwargs)
        return super(ColourField, self).formfield(*args, **defaults)
    
    def db_type(self, connection):
        return 'char(7)'
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.