Skip to content

Commit b82cc19

Browse files
committed
Add random color when saving label
1 parent b704759 commit b82cc19

3 files changed

Lines changed: 21 additions & 3 deletions

File tree

apps/learn/colors.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import random
2+
import string
13
from typing import Tuple
24

35
BLACK = '000000'
@@ -16,3 +18,10 @@ def get_luminance(red, green, blue, alpha) -> int:
1618
luminance = 0.2126 * red + 0.7152 * green + 0.0722 * blue
1719
luminance *= alpha / 255
1820
return round(luminance)
21+
22+
23+
def get_random_hex_color(include_alpha=False):
24+
size = 8 if include_alpha else 6
25+
return ''.join(
26+
random.choice(string.hexdigits.upper()) for _ in range(size)
27+
)

apps/learn/models.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import re
2+
13
from django.db import models
24

35
from . import colors
@@ -10,7 +12,9 @@ class Meta:
1012
name = models.CharField(max_length=120)
1113
slug = models.SlugField(max_length=120, unique=True)
1214
# Label color in hex mode
13-
color = models.CharField(max_length=8, default='FF0000')
15+
color = models.CharField(
16+
max_length=8, default=colors.get_random_hex_color()
17+
)
1418

1519
def __str__(self):
1620
return self.name
@@ -21,6 +25,10 @@ def foreground_color(self):
2125
luminance = colors.get_luminance(*rgb_color)
2226
return colors.BLACK if luminance > 128 else colors.WHITE
2327

28+
def save(self, *args, **kwargs):
29+
self.color = re.sub(r'^#', '', self.color)
30+
super().save(*args, **kwargs)
31+
2432

2533
class Resource(models.Model):
2634
class Meta:

apps/learn/static/learn/css/main.scss

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@ a.label {
2020
border-radius: 12px;
2121
padding-top: 2px;
2222
padding-bottom: 2px;
23-
padding-left: 3px;
24-
padding-right: 3px;
23+
padding-left: 4px;
24+
padding-right: 4px;
25+
font-size: 12px;
2526
}
2627
}
2728

0 commit comments

Comments
 (0)