Fixes #672: Expanded color selection for rack and device roles

This commit is contained in:
Jeremy Stretch
2016-12-06 12:28:29 -05:00
parent 300ee820fa
commit eb4cd0e723
7 changed files with 139 additions and 51 deletions

View File

@@ -1,5 +1,11 @@
from django.core.validators import RegexValidator
from django.db import models
from .forms import ColorSelect
validate_color = RegexValidator('^[0-9a-f]{6}$', 'Enter a valid hexadecimal RGB color code.', 'invalid')
class NullableCharField(models.CharField):
description = "Stores empty values as NULL rather than ''"
@@ -11,3 +17,16 @@ class NullableCharField(models.CharField):
def get_prep_value(self, value):
return value or None
class ColorField(models.CharField):
default_validators = [validate_color]
description = "A hexadecimal RGB color code"
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 6
super(ColorField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
kwargs['widget'] = ColorSelect
return super(ColorField, self).formfield(**kwargs)

View File

@@ -11,6 +11,32 @@ from django.utils.html import format_html
from django.utils.safestring import mark_safe
COLOR_CHOICES = (
('aa1409', 'Dark red'),
('f44336', 'Red'),
('e91e63', 'Pink'),
('ff66ff', 'Fuschia'),
('9c27b0', 'Purple'),
('673ab7', 'Dark purple'),
('3f51b5', 'Indigo'),
('2196f3', 'Blue'),
('03a9f4', 'Light blue'),
('00bcd4', 'Cyan'),
('009688', 'Teal'),
('2f6a31', 'Dark green'),
('4caf50', 'Green'),
('8bc34a', 'Light green'),
('cddc39', 'Lime'),
('ffeb3b', 'Yellow'),
('ffc107', 'Amber'),
('ff9800', 'Orange'),
('ff5722', 'Dark orange'),
('795548', 'Brown'),
('c0c0c0', 'Light grey'),
('9e9e9e', 'Grey'),
('607d8b', 'Dark grey'),
('111111', 'Black'),
)
NUMERIC_EXPANSION_PATTERN = '\[(\d+-\d+)\]'
IP4_EXPANSION_PATTERN = '\[([0-9]{1,3}-[0-9]{1,3})\]'
IP6_EXPANSION_PATTERN = '\[([0-9a-f]{1,4}-[0-9a-f]{1,4})\]'
@@ -71,6 +97,27 @@ class SmallTextarea(forms.Textarea):
pass
class ColorSelect(forms.Select):
def __init__(self, *args, **kwargs):
kwargs['choices'] = COLOR_CHOICES
super(ColorSelect, self).__init__(*args, **kwargs)
def render_option(self, selected_choices, option_value, option_label):
if option_value is None:
option_value = ''
option_value = force_text(option_value)
if option_value in selected_choices:
selected_html = mark_safe(' selected')
if not self.allow_multiple_selected:
# Only allow for a single selection.
selected_choices.remove(option_value)
else:
selected_html = ''
return format_html('<option value="{}"{} style="background-color: #{}">{}</option>',
option_value, selected_html, option_value, force_text(option_label))
class SelectWithDisabled(forms.Select):
"""
Modified the stock Select widget to accept choices using a dict() for a label. The dict for each option must include