Skip to content

Instantly share code, notes, and snippets.

@LowerDeez
Last active March 21, 2018 15:33
Show Gist options
  • Save LowerDeez/81de2f1473ae6877adfef881b4ca57fa to your computer and use it in GitHub Desktop.
Save LowerDeez/81de2f1473ae6877adfef881b4ca57fa to your computer and use it in GitHub Desktop.
Django. Color Field
from django.core.validators import RegexValidator
 
 
class Project(models.Model):
    color = models.CharField(
        max_length=7,
        default="#fff",
        validators=[RegexValidator(
            "(^#[0-9a-fA-F]{3}$)|(^#[0-9a-fA-F]{6}$)")],
        verbose_name=_("color"),
        help_text=_("Enter the hex color code, like #ccc or #cccccc")
        )
from django.core.exceptions import ValidationError
 
 
class TestProjectModel(TestCase):
 
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create(
            username="taskbuster", password="django-tutorial")
        self.profile = self.user.profile
 
    def tearDown(self):
        self.user.delete()
 
    def test_validation_color(self):
        # This first project uses the default value, #fff
        project = models.Project(
            user=self.profile,
            name="TaskManager"
            )
        self.assertTrue(project.color == "#fff")
        # Validation shouldn't rise an Error
        project.full_clean()
 
        # Good color inputs (without Errors):
        for color in ["#1cA", "#1256aB"]:
            project.color = color
            project.full_clean()
 
        # Bad color inputs:
        for color in ["1cA", "1256aB", "#1", "#12", "#1234",
                      "#12345", "#1234567"]:
            with self.assertRaises(
                    ValidationError,
                    msg="%s didn't raise a ValidationError" % color):
                project.color = color
                project.full_clean()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment