or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Django Colorfield

1

2

Django 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.

3

4

## Package Information

5

6

- **Package Name**: django-colorfield

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Framework**: Django

10

- **Installation**: `pip install django-colorfield`

11

- **Setup**: Add `'colorfield'` to `INSTALLED_APPS` and run `python manage.py collectstatic`

12

13

## Core Imports

14

15

```python

16

from colorfield.fields import ColorField

17

from colorfield.forms import ColorField as ColorFormField

18

from colorfield.widgets import ColorWidget

19

```

20

21

For validators and utilities:

22

23

```python

24

from colorfield.validators import (

25

color_hex_validator,

26

color_hexa_validator,

27

color_rgb_validator,

28

color_rgba_validator,

29

COLOR_HEX_RE,

30

COLOR_HEXA_RE,

31

COLOR_RGB_RE,

32

COLOR_RGBA_RE

33

)

34

from colorfield.utils import (

35

get_image_file_background_color,

36

get_image_background_color,

37

get_random_string

38

)

39

from colorfield.fields import VALIDATORS_PER_FORMAT, DEFAULT_PER_FORMAT

40

```

41

42

For Django REST Framework integration (optional):

43

44

```python

45

from colorfield.serializers import ColorField as ColorSerializerField

46

```

47

48

## Basic Usage

49

50

```python

51

from django.db import models

52

from colorfield.fields import ColorField

53

54

# Basic model with color field

55

class MyModel(models.Model):

56

color = ColorField(default='#FF0000')

57

58

# Advanced usage with different formats and options

59

class AdvancedModel(models.Model):

60

hex_color = ColorField(format="hex", default="#FFFFFF")

61

hexa_color = ColorField(format="hexa", default="#FFFFFFFF")

62

rgb_color = ColorField(format="rgb", default="rgb(255, 255, 255)")

63

rgba_color = ColorField(format="rgba", default="rgba(255, 255, 255, 1)")

64

65

# Color with predefined samples (non-restrictive)

66

themed_color = ColorField(samples=[

67

("#FF0000", "Red"),

68

("#00FF00", "Green"),

69

("#0000FF", "Blue")

70

])

71

72

# Color with restrictive choices

73

status_color = ColorField(choices=[

74

("#FF0000", "Error"),

75

("#FFFF00", "Warning"),

76

("#00FF00", "Success")

77

])

78

79

# Auto-extract color from image

80

image = models.ImageField(upload_to="images/")

81

auto_color = ColorField(image_field="image")

82

83

# Using in forms

84

from django import forms

85

from colorfield.forms import ColorField as ColorFormField

86

87

class MyForm(forms.Form):

88

color = ColorFormField(initial="#FF0000")

89

```

90

91

## Capabilities

92

93

### Model Field

94

95

Django model field for storing color values with admin interface integration.

96

97

```python { .api }

98

class ColorField(CharField):

99

"""

100

Color field for Django models with color picker widget in admin.

101

102

Parameters:

103

- format: str, color format ('hex', 'hexa', 'rgb', 'rgba') (default: 'hex')

104

- samples: list, color palette samples [(color, label), ...] (optional)

105

- image_field: str, name of ImageField to extract color from (optional)

106

- Standard CharField parameters (max_length=25, default, null, blank, etc.)

107

108

Note: 'samples' and 'choices' are mutually exclusive

109

"""

110

111

def __init__(self, *args, **kwargs): ...

112

def formfield(self, **kwargs): ...

113

def contribute_to_class(self, cls, name, **kwargs): ...

114

def deconstruct(self): ...

115

def validate(self, value, *args, **kwargs): ...

116

```

117

118

### Form Field

119

120

Color field for Django forms (non-model forms) with color picker widget.

121

122

```python { .api }

123

class ColorField(forms.CharField):

124

"""

125

Color field for plain Django forms with color picker widget.

126

127

Parameters:

128

- validator: function, color validator (default: color_hex_validator)

129

- Standard CharField parameters

130

"""

131

132

def __init__(self, *args, **kwargs): ...

133

```

134

135

### Widget

136

137

HTML widget providing color picker interface using Coloris.js library.

138

139

```python { .api }

140

class ColorWidget(TextInput):

141

"""

142

Color picker widget for Django forms.

143

144

Attributes:

145

- template_name: str, template path ('colorfield/color.html')

146

- Media: CSS and JS files for Coloris color picker

147

"""

148

149

def get_context(self, name, value, attrs=None): ...

150

def render(self, name, value, attrs=None, renderer=None): ...

151

```

152

153

### Validators

154

155

Color format validation functions using Django's RegexValidator.

156

157

```python { .api }

158

def color_hex_validator(value):

159

"""

160

Validates hex color format (#RGB or #RRGGBB).

161

162

Parameters:

163

- value: str, color value to validate

164

165

Raises:

166

- ValidationError: if color format is invalid

167

"""

168

169

def color_hexa_validator(value):

170

"""

171

Validates hexa color format (#RGBA or #RRGGBBAA).

172

173

Parameters:

174

- value: str, color value to validate

175

176

Raises:

177

- ValidationError: if color format is invalid

178

"""

179

180

def color_rgb_validator(value):

181

"""

182

Validates RGB color format (rgb(r, g, b)).

183

184

Parameters:

185

- value: str, color value to validate

186

187

Raises:

188

- ValidationError: if color format is invalid

189

"""

190

191

def color_rgba_validator(value):

192

"""

193

Validates RGBA color format (rgba(r, g, b, a)).

194

195

Parameters:

196

- value: str, color value to validate

197

198

Raises:

199

- ValidationError: if color format is invalid

200

"""

201

```

202

203

### Utility Functions

204

205

Helper functions for color processing and image color extraction.

206

207

```python { .api }

208

def get_image_file_background_color(img_file, img_format):

209

"""

210

Extract color from image file.

211

212

Parameters:

213

- img_file: File, Django file object of image

214

- img_format: str, desired color format ('hex', 'hexa', 'rgb', 'rgba')

215

216

Returns:

217

- str: Color value in specified format, empty string if extraction fails

218

"""

219

220

def get_image_background_color(img, img_format):

221

"""

222

Extract color from PIL Image object (top-left pixel).

223

224

Parameters:

225

- img: PIL.Image, image object

226

- img_format: str, desired color format ('hex', 'hexa', 'rgb', 'rgba')

227

228

Returns:

229

- str: Color value in specified format

230

"""

231

232

def get_random_string():

233

"""

234

Generate random string for widget IDs.

235

236

Returns:

237

- str: 32-character random string (lowercase letters and digits)

238

"""

239

```

240

241

### DRF Serializer Field (Optional)

242

243

Django REST Framework integration for API serialization.

244

245

```python { .api }

246

class ColorField(CharField):

247

"""

248

Color field for Django REST Framework serializers.

249

Validates color in any supported format (hex, hexa, rgb, rgba).

250

251

Requires: djangorestframework package

252

"""

253

254

def to_internal_value(self, data): ...

255

```

256

257

## Types

258

259

### Color Format Constants

260

261

```python { .api }

262

# Default values per format

263

DEFAULT_PER_FORMAT = {

264

"hex": "#FFFFFF",

265

"hexa": "#FFFFFFFF",

266

"rgb": "rgb(255, 255, 255)",

267

"rgba": "rgba(255, 255, 255, 1)"

268

}

269

270

# Color samples format

271

ColorSample = tuple[str, str] # (color_value, label)

272

ColorPalette = list[ColorSample]

273

```

274

275

### Regular Expression Patterns

276

277

```python { .api }

278

import re

279

280

COLOR_HEX_RE = re.compile("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$")

281

COLOR_HEXA_RE = re.compile("#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{4})$")

282

COLOR_RGB_RE = re.compile(r"^rgb\((\d{1,3}),\s?(\d{1,3}),\s?(\d{1,3})\)$")

283

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)?)\)$")

284

```

285

286

## Error Handling

287

288

The package provides comprehensive validation through Django's validation system:

289

290

- **ValidationError**: Raised for invalid color formats during model validation

291

- **ImproperlyConfigured**: Raised for invalid field configuration (e.g., using both 'choices' and 'samples', invalid image_field reference)

292

- **FieldDoesNotExist**: Raised when specified image_field doesn't exist on the model

293

- **UnidentifiedImageError**: Handled gracefully during image color extraction, returns empty string

294

295

## Admin Integration

296

297

Django Colorfield automatically provides a color picker widget in the Django admin interface:

298

299

- Uses Coloris.js library for the color picker functionality

300

- Supports both DEBUG and production CSS/JS asset loading

301

- Automatically detects color format and enables/disables alpha channel

302

- Displays color swatches when samples or choices are provided

303

- Integrates seamlessly with Django's admin form validation