Color field for Django models with a nice color-picker in the admin interface
npx @tessl/cli install tessl/pypi-django-colorfield@0.14.0Django Colorfield provides a color field for Django models with an integrated color picker widget in the Django admin interface. It supports multiple color formats (hex, hexa, rgb, rgba), automatic color extraction from images, customizable color palette samples, and seamless integration with both Django model forms and plain forms.
pip install django-colorfield'colorfield' to INSTALLED_APPS and run python manage.py collectstaticfrom colorfield.fields import ColorField
from colorfield.forms import ColorField as ColorFormField
from colorfield.widgets import ColorWidgetFor validators and utilities:
from colorfield.validators import (
color_hex_validator,
color_hexa_validator,
color_rgb_validator,
color_rgba_validator,
COLOR_HEX_RE,
COLOR_HEXA_RE,
COLOR_RGB_RE,
COLOR_RGBA_RE
)
from colorfield.utils import (
get_image_file_background_color,
get_image_background_color,
get_random_string
)
from colorfield.fields import VALIDATORS_PER_FORMAT, DEFAULT_PER_FORMATFor Django REST Framework integration (optional):
from colorfield.serializers import ColorField as ColorSerializerFieldfrom django.db import models
from colorfield.fields import ColorField
# Basic model with color field
class MyModel(models.Model):
color = ColorField(default='#FF0000')
# Advanced usage with different formats and options
class AdvancedModel(models.Model):
hex_color = ColorField(format="hex", default="#FFFFFF")
hexa_color = ColorField(format="hexa", default="#FFFFFFFF")
rgb_color = ColorField(format="rgb", default="rgb(255, 255, 255)")
rgba_color = ColorField(format="rgba", default="rgba(255, 255, 255, 1)")
# Color with predefined samples (non-restrictive)
themed_color = ColorField(samples=[
("#FF0000", "Red"),
("#00FF00", "Green"),
("#0000FF", "Blue")
])
# Color with restrictive choices
status_color = ColorField(choices=[
("#FF0000", "Error"),
("#FFFF00", "Warning"),
("#00FF00", "Success")
])
# Auto-extract color from image
image = models.ImageField(upload_to="images/")
auto_color = ColorField(image_field="image")
# Using in forms
from django import forms
from colorfield.forms import ColorField as ColorFormField
class MyForm(forms.Form):
color = ColorFormField(initial="#FF0000")Django model field for storing color values with admin interface integration.
class ColorField(CharField):
"""
Color field for Django models with color picker widget in admin.
Parameters:
- format: str, color format ('hex', 'hexa', 'rgb', 'rgba') (default: 'hex')
- samples: list, color palette samples [(color, label), ...] (optional)
- image_field: str, name of ImageField to extract color from (optional)
- Standard CharField parameters (max_length=25, default, null, blank, etc.)
Note: 'samples' and 'choices' are mutually exclusive
"""
def __init__(self, *args, **kwargs): ...
def formfield(self, **kwargs): ...
def contribute_to_class(self, cls, name, **kwargs): ...
def deconstruct(self): ...
def validate(self, value, *args, **kwargs): ...Color field for Django forms (non-model forms) with color picker widget.
class ColorField(forms.CharField):
"""
Color field for plain Django forms with color picker widget.
Parameters:
- validator: function, color validator (default: color_hex_validator)
- Standard CharField parameters
"""
def __init__(self, *args, **kwargs): ...HTML widget providing color picker interface using Coloris.js library.
class ColorWidget(TextInput):
"""
Color picker widget for Django forms.
Attributes:
- template_name: str, template path ('colorfield/color.html')
- Media: CSS and JS files for Coloris color picker
"""
def get_context(self, name, value, attrs=None): ...
def render(self, name, value, attrs=None, renderer=None): ...Color format validation functions using Django's RegexValidator.
def color_hex_validator(value):
"""
Validates hex color format (#RGB or #RRGGBB).
Parameters:
- value: str, color value to validate
Raises:
- ValidationError: if color format is invalid
"""
def color_hexa_validator(value):
"""
Validates hexa color format (#RGBA or #RRGGBBAA).
Parameters:
- value: str, color value to validate
Raises:
- ValidationError: if color format is invalid
"""
def color_rgb_validator(value):
"""
Validates RGB color format (rgb(r, g, b)).
Parameters:
- value: str, color value to validate
Raises:
- ValidationError: if color format is invalid
"""
def color_rgba_validator(value):
"""
Validates RGBA color format (rgba(r, g, b, a)).
Parameters:
- value: str, color value to validate
Raises:
- ValidationError: if color format is invalid
"""Helper functions for color processing and image color extraction.
def get_image_file_background_color(img_file, img_format):
"""
Extract color from image file.
Parameters:
- img_file: File, Django file object of image
- img_format: str, desired color format ('hex', 'hexa', 'rgb', 'rgba')
Returns:
- str: Color value in specified format, empty string if extraction fails
"""
def get_image_background_color(img, img_format):
"""
Extract color from PIL Image object (top-left pixel).
Parameters:
- img: PIL.Image, image object
- img_format: str, desired color format ('hex', 'hexa', 'rgb', 'rgba')
Returns:
- str: Color value in specified format
"""
def get_random_string():
"""
Generate random string for widget IDs.
Returns:
- str: 32-character random string (lowercase letters and digits)
"""Django REST Framework integration for API serialization.
class ColorField(CharField):
"""
Color field for Django REST Framework serializers.
Validates color in any supported format (hex, hexa, rgb, rgba).
Requires: djangorestframework package
"""
def to_internal_value(self, data): ...# Default values per format
DEFAULT_PER_FORMAT = {
"hex": "#FFFFFF",
"hexa": "#FFFFFFFF",
"rgb": "rgb(255, 255, 255)",
"rgba": "rgba(255, 255, 255, 1)"
}
# Color samples format
ColorSample = tuple[str, str] # (color_value, label)
ColorPalette = list[ColorSample]import re
COLOR_HEX_RE = re.compile("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$")
COLOR_HEXA_RE = re.compile("#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{4})$")
COLOR_RGB_RE = re.compile(r"^rgb\((\d{1,3}),\s?(\d{1,3}),\s?(\d{1,3})\)$")
COLOR_RGBA_RE = re.compile(r"^rgba\((\d{1,3}),\s?(\d{1,3}),\s?(\d{1,3}),\s?(0(\.\d{1,2})?|1(\.0)?)\)$")The package provides comprehensive validation through Django's validation system:
Django Colorfield automatically provides a color picker widget in the Django admin interface: