### Install and Test Django Colorfield Source: https://github.com/fabiocaccamo/django-colorfield/blob/main/README.md Instructions for cloning the repository, setting up a virtual environment, installing dependencies, and running tests using tox or Django's test runner. ```bash # clone repository git clone https://github.com/fabiocaccamo/django-colorfield.git && cd django-colorfield # create virtualenv and activate it python -m venv venv && . venv/bin/activate # upgrade pip python -m pip install --upgrade pip # install requirements pip install -r requirements.txt -r requirements-test.txt # install pre-commit to run formatters and linters pre-commit install --install-hooks # run tests tox # or python runtests.py # or python -m django test --settings "tests.settings" ``` -------------------------------- ### Install Django Colorfield Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Install the package using pip and add 'colorfield' to INSTALLED_APPS in settings.py. Collect static files and restart the server. ```bash pip install django-colorfield ``` ```python # settings.py INSTALLED_APPS = [ # ... "colorfield", # ... ] ``` ```bash python manage.py collectstatic # Restart your application server ``` -------------------------------- ### Instantiate ColorWidget Manually with Attributes Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Manually instantiate ColorWidget and configure its attributes for the color picker. Supported attributes include format, alpha slider, swatches, swatch-only mode, required status, and default color. ```python from colorfield.widgets import ColorWidget from django import forms # Manual widget instantiation with all supported attrs widget = ColorWidget(attrs={ "format": "hex", # "hex", "rgb", or "rgba" "alpha": False, # True enables alpha slider "swatches": ["#FF0000", "#00FF00", "#0000FF"], "swatches_only": False, # True restricts picker to swatches only "required": True, # False adds a "Clear" button to the picker "default": "#FF0000", # Initial color shown in picker }) ``` -------------------------------- ### Inspect ColorWidget Media Assets Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Access and print the CSS and JavaScript assets loaded by the ColorWidget's Media class. This demonstrates how the widget ensures the correct static files for the color picker are included. ```python from colorfield.widgets import ColorWidget from django import forms # The widget's Media class ensures correct static files are included: widget = ColorWidget() print(widget.media._css) # {'all': ['colorfield/coloris/coloris.min.css']} print(widget.media._js) # ['colorfield/coloris/coloris.min.js', 'colorfield/colorfield.js'] ``` -------------------------------- ### Samples vs Choices for ColorField Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Use `samples` for a non-restrictive color swatch palette in the UI, or `choices` for strict validation against a predefined list of colors. These options are mutually exclusive. ```python from colorfield.fields import ColorField from django.db import models from django.core.exceptions import ImproperlyConfigured, ValidationError COLOR_PALETTE = [ ("#FFFFFF", "White"), ("#000000", "Black"), ("#FF0000", "Red"), ] class ArticleTag(models.Model): # samples: palette shown as swatches, but any color is accepted color = ColorField(samples=COLOR_PALETTE, default="#FF0000") class StrictTag(models.Model): # choices: ONLY listed colors are valid (case-insensitive) color = ColorField(choices=COLOR_PALETTE, default="#FF0000") # samples — allows colors outside the palette tag = ArticleTag(color="#35B6A3") tag.full_clean() # OK — no ValidationError tag.save() # choices — enforces palette membership strict = StrictTag(color="#35B6A3") try: strict.full_clean() except ValidationError as e: print(e) # ValidationError: color is not a valid choice strict2 = StrictTag(color="#ffffff") # case-insensitive match strict2.full_clean() # OK strict2.save() # Using both raises ImproperlyConfigured immediately at field definition try: bad_field = ColorField(choices=COLOR_PALETTE, samples=COLOR_PALETTE) except ImproperlyConfigured as e: print(e) # "Invalid options: 'choices' and 'samples' are mutually exclusive..." ``` -------------------------------- ### Provide Color Palette for Widget Source: https://github.com/fabiocaccamo/django-colorfield/blob/main/README.md Enhance the color picker widget by providing a predefined palette of colors using the 'samples' option. This is not restrictive; users can still select colors outside the palette. ```python from colorfield.fields import ColorField from django.db import models class MyModel(models.Model): COLOR_PALETTE = [ ("#FFFFFF", "white", ), ("#000000", "black", ), ] # not restrictive, allows the selection of another color from the spectrum. color = ColorField(samples=COLOR_PALETTE) # restrictive, it is mandatory to choose a color from the palette color = ColorField(choices=COLOR_PALETTE) ``` -------------------------------- ### Usage in a Django View Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Demonstrates how to handle color data submitted through a Django form in a view. Ensure the form is correctly defined to include color fields. ```python from django.shortcuts import render from django.forms import ModelForm # Assuming ThemeForm and BrandConfig are defined elsewhere # from .forms import ThemeForm # from myapp.models import BrandConfig def my_view(request): if request.method == "POST": form = ThemeForm(request.POST) if form.is_valid(): bg = form.cleaned_data["background"] # e.g. "#1A2B3C" fg = form.cleaned_data["foreground"] # e.g. "#FFFFFF" # ... persist or use values else: form = ThemeForm() return render(request, "theme.html", {"form": form}) ``` ```python from django.forms import ModelForm from myapp.models import BrandConfig class BrandConfigForm(ModelForm): class Meta: model = BrandConfig fields = ["primary_color", "accent_color"] # ColorWidget is automatically applied; no extra configuration needed ``` -------------------------------- ### Configure ColorField Format Source: https://github.com/fabiocaccamo/django-colorfield/blob/main/README.md Specify the desired color format for the ColorField. Supported formats include 'hex', 'hexa', 'rgb', and 'rgba'. Defaults to 'hex'. ```python from colorfield.fields import ColorField from django.db import models class MyModel(models.Model): color = ColorField(format="hexa") ``` -------------------------------- ### Automatic ColorWidget Integration in Django Admin Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Demonstrates that ColorWidget is automatically integrated into the Django admin for ColorField fields. No explicit code is required in the admin.py file for the color picker to appear. ```python # In Django admin, ColorWidget is wired automatically — no extra code needed: # admin.py from django.contrib import admin from myapp.models import BrandConfig @admin.register(BrandConfig) class BrandConfigAdmin(admin.ModelAdmin): pass # The color picker appears automatically for all ColorField fields. ``` -------------------------------- ### Auto-populate Color from Image Field Source: https://github.com/fabiocaccamo/django-colorfield/blob/main/README.md Use the 'image_field' option to automatically set the color value from the top-left pixel of an associated ImageField upon saving the model instance. ```python from colorfield.fields import ColorField from django.db import models class MyModel(models.Model): image = models.ImageField(upload_to="images") color = ColorField(image_field="image") ``` -------------------------------- ### Color Validators Direct Usage Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Provides standalone `RegexValidator` instances for direct use in forms, serializers, or other validation contexts. Includes validators for hex, hexa, rgb, and rgba formats. ```python from django.core.exceptions import ValidationError from colorfield.validators import ( color_hex_validator, color_hexa_validator, color_rgb_validator, color_rgba_validator, ) # Use validators directly def validate_user_color(value: str) -> None: """Accept hex or rgb, reject everything else.""" hex_ok = True rgb_ok = True try: color_hex_validator(value) hex_ok = True except ValidationError: hex_ok = False try: color_rgb_validator(value) rgb_ok = True except ValidationError: rgb_ok = False if not (hex_ok or rgb_ok): raise ValidationError(f"'{value}' is not a valid hex or rgb color.") validate_user_color("#FF0000") # OK validate_user_color("rgb(0, 128, 255)") # OK try: validate_user_color("red") except ValidationError as e: print(e) # ValidationError: 'red' is not a valid hex or rgb color. ``` ```python # Attach to a plain Django form field from django import forms class ColorInputForm(forms.Form): hex_color = forms.CharField(validators=[color_hex_validator]) hexa_color = forms.CharField(validators=[color_hexa_validator]) rgb_color = forms.CharField(validators=[color_rgb_validator]) rgba_color = forms.CharField(validators=[color_rgba_validator]) form = ColorInputForm(data={ "hex_color": "#1A2B3C", "hexa_color": "#1A2B3CFF", "rgb_color": "rgb(26, 43, 60)", "rgba_color": "rgba(26, 43, 60, 1)", }) print(form.is_valid()) # True bad_form = ColorInputForm(data={ "hex_color": "blue", "hexa_color": "#1A2B3CFF", "rgb_color": "rgb(26, 43, 60)", "rgba_color": "rgba(26, 43, 60, 1)", }) print(bad_form.is_valid()) # False print(bad_form.errors) # {'hex_color': ['Enter a valid hex color, eg. #000000']} ``` -------------------------------- ### Add ColorField to Django Model Source: https://github.com/fabiocaccamo/django-colorfield/blob/main/README.md Integrate the ColorField into your Django models. Ensure 'colorfield' is in INSTALLED_APPS and run collectstatic. ```python from colorfield.fields import ColorField from django.db import models class MyModel(models.Model): color = ColorField(default='#FF0000') ``` -------------------------------- ### Standalone Form Field with Coloris Widget Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Integrate the Coloris color-picker widget into any Django form using `colorfield.forms.ColorField`. Defaults to hex validation; provide a custom `validator` for other formats like RGBA. ```python from django import forms from colorfield.forms import ColorField from colorfield.validators import color_rgba_validator # Basic hex form field class ThemeForm(forms.Form): background = ColorField(initial="#FFFFFF") foreground = ColorField(initial="#000000") # Custom validator for rgba format class AdvancedThemeForm(forms.Form): overlay = ColorField( initial="rgba(0, 0, 0, 0.5)", validator=color_rgba_validator, required=False, ) ``` -------------------------------- ### Auto-Extract Color from Image Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Automatically populate a `ColorField` with the color of the top-left pixel of an associated `ImageField` on model save. Requires Pillow. The `format` can be set to 'hexa', 'rgb', or 'rgba'. ```python from colorfield.fields import ColorField from django.db import models class Product(models.Model): image = models.ImageField(upload_to="products/") # Automatically populated from top-left pixel of `image` on save dominant_color = ColorField(image_field="image") class ProductHexa(models.Model): image = models.ImageField(upload_to="products/") # Same but stores in hexa format (with alpha channel) dominant_color = ColorField(image_field="image", format="hexa") class ProductRGB(models.Model): image = models.ImageField(upload_to="products/") color_rgb = ColorField(image_field="image", format="rgb") color_rgba = ColorField(image_field="image", format="rgba") # Usage: assign image → save → color auto-populated from django.core.files import File product = Product() with open("/path/to/logo.png", "rb") as f: product.image.save("logo.png", File(f), save=False) product.save() print(product.dominant_color) # e.g. "#082D20" (hex of top-left pixel) # Hexa variant also captures alpha p2 = ProductHexa() with open("/path/to/logo.png", "rb") as f: p2.image.save("logo.png", File(f), save=False) p2.save() print(p2.dominant_color) # e.g. "#082D20FF" # RGB variants p3 = ProductRGB() with open("/path/to/logo.png", "rb") as f: p3.image.save("logo.png", File(f), save=False) p3.save() print(p3.color_rgb) # e.g. "rgb(8, 45, 32)" print(p3.color_rgba) # e.g. "rgba(8, 45, 32, 1.0)" ``` -------------------------------- ### Configure ColorField Format Option Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt The 'format' option in ColorField determines how color values are stored and validated. Supported formats include 'hex', 'hexa', 'rgb', and 'rgba'. ```python from colorfield.fields import ColorField from django.db import models class Palette(models.Model): # hex: #RRGGBB (3 or 6 hex digits, case-insensitive) hex_color = ColorField(format="hex", default="#FF5733") # hexa: #RRGGBBAA (4 or 8 hex digits) hexa_color = ColorField(format="hexa", default="#FF5733CC") # rgb: rgb(R, G, B) — each channel 0-255 rgb_color = ColorField(format="rgb", default="rgb(255, 87, 51)") # rgba: rgba(R, G, B, A) — alpha 0.0-1.0 (up to 2 decimal places) rgba_color = ColorField(format="rgba", default="rgba(255, 87, 51, 0.80)") ``` -------------------------------- ### Use ColorField in Django Forms Source: https://github.com/fabiocaccamo/django-colorfield/blob/main/README.md Use `colorfield.forms.ColorField` in plain Django forms for color input outside of a model context. Specify initial color and format. ```python from django import forms from colorfield.forms import ColorField class MyForm(forms.Form): color = ColorField(initial="#FF0000", format="hex") ``` -------------------------------- ### Color Validators Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Standalone `RegexValidator` instances for hex, hexa, rgb, and rgba colors that can be used directly in forms, serializers, or any place Django validators are accepted. ```APIDOC ## Color Validators ### Description Four standalone `RegexValidator` instances are available for use directly in forms, serializers, or anywhere Django validators are accepted: `color_hex_validator`, `color_hexa_validator`, `color_rgb_validator`, `color_rgba_validator`. ### Usage ```python from django.core.exceptions import ValidationError from colorfield.validators import ( color_hex_validator, color_hexa_validator, color_rgb_validator, color_rgba_validator, ) # Use validators directly def validate_user_color(value: str) -> None: """Accept hex or rgb, reject everything else.""" hex_ok = True rgb_ok = True try: color_hex_validator(value) hex_ok = True except ValidationError: hex_ok = False try: color_rgb_validator(value) rgb_ok = True except ValidationError: rgb_ok = False if not (hex_ok or rgb_ok): raise ValidationError(f"'{value}' is not a valid hex or rgb color.") validate_user_color("#FF0000") # OK validate_user_color("rgb(0, 128, 255)") # OK try: validate_user_color("red") except ValidationError as e: print(e) # ValidationError: 'red' is not a valid hex or rgb color. # Attach to a plain Django form field from django import forms class ColorInputForm(forms.Form): hex_color = forms.CharField(validators=[color_hex_validator]) hexa_color = forms.CharField(validators=[color_hexa_validator]) rgb_color = forms.CharField(validators=[color_rgb_validator]) rgba_color = forms.CharField(validators=[color_rgba_validator]) form = ColorInputForm(data={ "hex_color": "#1A2B3C", "hexa_color": "#1A2B3CFF", "rgb_color": "rgb(26, 43, 60)", "rgba_color": "rgba(26, 43, 60, 1)", }) print(form.is_valid()) # True bad_form = ColorInputForm(data={ "hex_color": "blue", "hexa_color": "#1A2B3CFF", "rgb_color": "rgb(26, 43, 60)", "rgba_color": "rgba(26, 43, 60, 1)", }) print(bad_form.is_valid()) # False print(bad_form.errors) # {'hex_color': ['Enter a valid hex color, eg. #000000']} ``` ``` -------------------------------- ### Define Model with ColorField Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Use ColorField in Django models to store color values. It supports hex, hexa, rgb, and rgba formats, with options for nullability, blank fields, restricted choices, and suggested samples. ```python from colorfield.fields import ColorField from django.db import models # -- Basic hex color field (default) -- class BrandConfig(models.Model): primary_color = ColorField(default="#3498DB") # hex (default) accent_color = ColorField(format="hexa", default="#E74C3CFF") # with alpha bg_color = ColorField(format="rgb", default="rgb(255, 255, 255)") overlay_color = ColorField(format="rgba", default="rgba(0, 0, 0, 0.5)") # Nullable field - stores NULL when no color is chosen optional_color = ColorField(null=True) # Blank field - stores empty string when no color is chosen clearable_color = ColorField(blank=True) # -- Restricted to a palette using choices (enforced) -- class Theme(models.Model): COLOR_CHOICES = [ ("#FFFFFF", "White"), ("#000000", "Black"), ("#FF0000", "Red"), ] color = ColorField(choices=COLOR_CHOICES, default="#FFFFFF") # Validation: assigning a color outside COLOR_CHOICES raises ValidationError # -- Palette suggestions using samples (non-restrictive) -- class Tag(models.Model): SUGGESTED_COLORS = [ ("#E74C3C", "Red"), ("#3498DB", "Blue"), ("#2ECC71", "Green"), ] # User can still pick any color beyond the suggested swatches color = ColorField(samples=SUGGESTED_COLORS, default="#3498DB") # -- Creating and saving instances -- brand = BrandConfig(primary_color="#1ABC9C", overlay_color="rgba(0,0,0,0.75)") brand.save() print(brand.primary_color) # "#1ABC9C" print(brand.overlay_color) # "rgba(0,0,0,0.75)" tag = Tag(color="#9B59B6") # value outside samples is accepted tag.save() print(tag.color) # "#9B59B6" # -- choices ARE restrictive; invalid value raises ValidationError -- from django.core.exceptions import ValidationError theme = Theme(color="#ABCDEF") try: theme.full_clean() except ValidationError as e: print(e) # ValidationError: ['Value #ABCDEF is not a valid choice.'] ``` -------------------------------- ### Model Field Validation Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Demonstrates validation of different color formats (hex, hexa, rgb, rgba) on a Django model. Use `full_clean()` for validation before saving. ```python from colorfield.fields import ColorField from django.db import models class Palette(models.Model): hex_color = ColorField(default="#FFFFFF") hexa_color = ColorField(default="#FFFFFFFF", format="hexa") rgb_color = ColorField(default="rgb(255, 255, 255)", format="rgb") rgba_color = ColorField(default="rgba(255, 255, 255, 1.0)", format="rgba") p = Palette( hex_color="invalid", hexa_color="#FF5733CC", rgb_color="rgb(255, 87, 51)", rgba_color="rgba(255, 87, 51, 0.80)", ) try: p.full_clean() except Exception as e: print(e) # ValidationError on hex_color: "Enter a valid hex color, eg. #000000" # Valid instance p2 = Palette( hex_color="#FF5733", hexa_color="#FF5733CC", rgb_color="rgb(255, 87, 51)", rgba_color="rgba(255, 87, 51, 0.80)", ) p2.full_clean() # No exception p2.save() ``` -------------------------------- ### Use ColorField in Django Model Form Source: https://github.com/fabiocaccamo/django-colorfield/blob/main/README.md Integrate the ColorField into a Django model form. The widget automatically provides a color picker, and the field validates the color format based on the 'format' option. ```python from django import forms class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ["color"] ``` -------------------------------- ### Django REST Framework Serializer Field Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Utilizes the ColorField serializer for DRF to accept various color formats (hex, hexa, rgb, rgba) during deserialization. Raises ValidationError for invalid inputs. Requires `djangorestframework`. ```python from rest_framework import serializers from colorfield.serializers import ColorField class BrandSerializer(serializers.Serializer): name = serializers.CharField() color = ColorField() # accepts hex, hexa, rgb, or rgba # Valid inputs — all accepted for valid_color in ["#FF5733", "#FF5733CC", "rgb(255, 87, 51)", "rgba(255, 87, 51, 0.8)"]: s = BrandSerializer(data={"name": "Acme", "color": valid_color}) assert s.is_valid(), s.errors print(s.validated_data) # {'name': 'Acme', 'color': '#FF5733'} (or respective format) ``` ```python # Invalid input — raises ValidationError s = BrandSerializer(data={"name": "Acme", "color": "not-a-color"}) if not s.is_valid(): print(s.errors) # {'color': ['Enter a valid hex color, eg. #000000', # 'Enter a valid hexa color, eg. #00000000', # 'Enter a valid rgb color, eg. rgb(128, 128, 128)', # 'Enter a valid rgba color, eg. rgba(128, 128, 128, 0.5)']} ``` ```python # ModelSerializer — field is automatically mapped from rest_framework.serializers import ModelSerializer from myapp.models import BrandConfig class BrandConfigSerializer(ModelSerializer): class Meta: model = BrandConfig fields = ["id", "primary_color", "accent_color"] # primary_color / accent_color are auto-mapped to colorfield.serializers.ColorField ``` -------------------------------- ### Embed ColorWidget in a Custom Django Form Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt Embed the ColorWidget within a custom Django form field. This allows for specific configuration of the color picker for individual form fields, such as setting the format and alpha slider. ```python from colorfield.widgets import ColorWidget from django import forms # Embed in a custom form field class ManualColorForm(forms.Form): accent = forms.CharField( widget=ColorWidget(attrs={"format": "rgb", "alpha": False}), initial="rgb(255, 0, 0)", ) ``` -------------------------------- ### ColorField Serializer Source: https://context7.com/fabiocaccamo/django-colorfield/llms.txt The ColorField serializer is a CharField subclass for DRF that accepts hex, hexa, rgb, or rgba color formats during deserialization. It raises a ValidationError if the input does not match any valid color format. ```APIDOC ## `colorfield.serializers.ColorField` ### Description A DRF `CharField` subclass that accepts any of the four supported color formats (`hex`, `hexa`, `rgb`, `rgba`) during deserialization. If the input does not match any valid color format, a `ValidationError` listing all format error messages is raised. Requires `djangorestframework` to be installed. ### Request Example ```python from rest_framework import serializers from colorfield.serializers import ColorField class BrandSerializer(serializers.Serializer): name = serializers.CharField() color = ColorField() # accepts hex, hexa, rgb, or rgba # Valid inputs — all accepted for valid_color in ["#FF5733", "#FF5733CC", "rgb(255, 87, 51)", "rgba(255, 87, 51, 0.8)"]: s = BrandSerializer(data={"name": "Acme", "color": valid_color}) assert s.is_valid(), s.errors print(s.validated_data) # {'name': 'Acme', 'color': '#FF5733'} (or respective format) # Invalid input — raises ValidationError s = BrandSerializer(data={"name": "Acme", "color": "not-a-color"}) if not s.is_valid(): print(s.errors) # {'color': ['Enter a valid hex color, eg. #000000', # 'Enter a valid hexa color, eg. #00000000', # 'Enter a valid rgb color, eg. rgb(128, 128, 128)', # 'Enter a valid rgba color, eg. rgba(128, 128, 128, 0.5)']} # ModelSerializer — field is automatically mapped from rest_framework.serializers import ModelSerializer from myapp.models import BrandConfig class BrandConfigSerializer(ModelSerializer): class Meta: model = BrandConfig fields = ["id", "primary_color", "accent_color"] # primary_color / accent_color are auto-mapped to colorfield.serializers.ColorField ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.