2016-12-06 12:28:29 -05:00
|
|
|
from django.core.validators import RegexValidator
|
2016-03-01 11:23:03 -05:00
|
|
|
from django.db import models
|
|
|
|
|
2016-12-06 12:28:29 -05:00
|
|
|
from .forms import ColorSelect
|
|
|
|
|
2018-07-30 14:00:37 -04:00
|
|
|
ColorValidator = RegexValidator(
|
|
|
|
regex='^[0-9a-f]{6}$',
|
|
|
|
message='Enter a valid hexadecimal RGB color code.',
|
|
|
|
code='invalid'
|
|
|
|
)
|
2016-12-06 12:28:29 -05:00
|
|
|
|
2016-03-01 11:23:03 -05:00
|
|
|
|
|
|
|
class NullableCharField(models.CharField):
|
|
|
|
description = "Stores empty values as NULL rather than ''"
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
if isinstance(value, models.CharField):
|
|
|
|
return value
|
|
|
|
return value or ''
|
|
|
|
|
|
|
|
def get_prep_value(self, value):
|
|
|
|
return value or None
|
2016-12-06 12:28:29 -05:00
|
|
|
|
|
|
|
|
|
|
|
class ColorField(models.CharField):
|
2018-07-30 14:00:37 -04:00
|
|
|
default_validators = [ColorValidator]
|
2016-12-06 12:28:29 -05:00
|
|
|
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)
|