187π
import random
r = lambda: random.randint(0,255)
print('#%02X%02X%02X' % (r(),r(),r()))
64π
Here is a simple way:
import random
color = "%06x" % random.randint(0, 0xFFFFFF)
To generate a random 3 char color:
import random
color = "%03x" % random.randint(0, 0xFFF)
%x
in C-based languages is a string formatter to format integers as hexadecimal strings while 0x
is the prefix to write numbers in base-16.
Colors can be prefixed with β#β if needed (CSS style)
- [Django]-Get the list of checkbox post in django views
- [Django]-Django form fails validation on a unique field
- [Django]-Specifying a mySQL ENUM in a Django model
14π
little late to the party,
import random
chars = '0123456789ABCDEF'
['#'+''.join(random.sample(chars,6)) for i in range(N)]
- [Django]-The right place to keep my signals.py file in a Django project
- [Django]-Django.db.utils.ProgrammingError: relation "bot_trade" does not exist
- [Django]-Django: Model Form "object has no attribute 'cleaned_data'"
11π
Store it as a HTML color value:
Updated: now accepts both integer (0-255) and float (0.0-1.0) arguments. These will be clamped to their allowed range.
def htmlcolor(r, g, b):
def _chkarg(a):
if isinstance(a, int): # clamp to range 0--255
if a < 0:
a = 0
elif a > 255:
a = 255
elif isinstance(a, float): # clamp to range 0.0--1.0 and convert to integer 0--255
if a < 0.0:
a = 0
elif a > 1.0:
a = 255
else:
a = int(round(a*255))
else:
raise ValueError('Arguments must be integers or floats.')
return a
r = _chkarg(r)
g = _chkarg(g)
b = _chkarg(b)
return '#{:02x}{:02x}{:02x}'.format(r,g,b)
Result:
In [14]: htmlcolor(250,0,0)
Out[14]: '#fa0000'
In [15]: htmlcolor(127,14,54)
Out[15]: '#7f0e36'
In [16]: htmlcolor(0.1, 1.0, 0.9)
Out[16]: '#19ffe5'
- [Django]-How do I check for last loop iteration in Django template?
- [Django]-Why does Django's render() function need the "request" argument?
- [Django]-How to update an existing Conda environment with a .yml file
10π
This has been done before. Rather than implementing this yourself, possibly introducing errors, you may want to use a ready library, for example Faker. Have a look at the color providers, in particular hex_digit
.
In [1]: from faker import Factory
In [2]: fake = Factory.create()
In [3]: fake.hex_color()
Out[3]: u'#3cae6a'
In [4]: fake.hex_color()
Out[4]: u'#5a9e28'
- [Django]-How can I use the variables from "views.py" in JavasScript, "<script></script>" in a Django template?
- [Django]-Dynamically adding a form to a Django formset
- [Django]-Creating a JSON response using Django and Python
4π
Just store them as an integer with the three channels at different bit offsets (just like they are often stored in memory):
value = (red << 16) + (green << 8) + blue
(If each channel is 0-255). Store that integer in the database and do the reverse operation when you need to get back to the distinct channels.
- [Django]-What is the max size of 'max_length' in Django?
- [Django]-How to use pdb.set_trace() in a Django unittest?
- [Django]-How to get the name of current app within a template?
4π
import random
def hex_code_colors():
a = hex(random.randrange(0,256))
b = hex(random.randrange(0,256))
c = hex(random.randrange(0,256))
a = a[2:]
b = b[2:]
c = c[2:]
if len(a)<2:
a = "0" + a
if len(b)<2:
b = "0" + b
if len(c)<2:
c = "0" + c
z = a + b + c
return "#" + z.upper()
- [Django]-Django DRF with oAuth2 using DOT (django-oauth-toolkit)
- [Django]-How to tell if a task has already been queued in django-celery?
- [Django]-Django: add image in an ImageField from image url
3π
So many ways to do this, so hereβs a demo using βcolorutilsβ.
pip install colorutils
It is possible to generate random values in (RGB, HEX, WEB, YIQ, HSV).
# docs and downloads at
# https://pypi.python.org/pypi/colorutils/
from colorutils import random_web
from tkinter import Tk, Button
mgui = Tk()
mgui.geometry('150x28+400+200')
def rcolor():
rn = random_web()
print(rn) # for terminal watchers
cbutton.config(text=rn)
mgui.config(bg=rn)
cbutton = Button(text="Click", command=rcolor)
cbutton.pack()
mgui.mainloop()
I certainly hope that was helpful.
- [Django]-How to access array elements in a Django template?
- [Django]-Fastest way to get the first object from a queryset in django?
- [Django]-Django template can't see CSS files
3π
Basically, this will give you a hashtag, a randint that gets converted to hex, and a padding of zeroes.
from random import randint
color = '#{:06x}'.format(randint(0, 256**3))
#Use the colors wherever you need!
- [Django]-Django Rest Framework: Dynamically return subset of fields
- [Django]-Redirect to Next after login in Django
- [Django]-Django index page best/most common practice
3π
import secrets
# generate 4 sets of 2-digit hex chars for a color with transparency
rgba = f"#{secrets.token_hex(4)}" # example return: "#ffff0000"
# generate 3 sets of 2-digit hex chars for a non-alpha color
rgb = f"#{secrets.token_hex(3)}" # example return: "#ab12ce"
- [Django]-Count() vs len() on a Django QuerySet
- [Django]-Select distinct values from a table field
- [Django]-How to resize an ImageField image before saving it in python Django model
2π
import random
def generate_color():
color = '#{:02x}{:02x}{:02x}'.format(*map(lambda x: random.randint(0, 255), range(3)))
return color
- [Django]-Django β "no module named django.core.management"
- [Django]-Disable migrations when running unit tests in Django 1.7
- [Django]-How to get the current url namespace using Django?
1π
For generating random anything, take a look at the random module
I would suggest you use the module to generate a random integer, take itβs modulo 2**24
, and treat the top 8 bits as R, that middle 8 bits as G and the bottom 8 as B.
It can all be accomplished with div/mod or bitwise operations.
- [Django]-How to use Django ImageField, and why use it at all?
- [Django]-Alowing 'fuzzy' translations in django pages?
- [Django]-What are the limitations of Django's ORM?
1π
hex_digits = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
digit_array = []
for i in xrange(6):
digit_array.append(hex_digits[randint(0,15)])
joined_digits = ''.join(digit_array)
color = '#' + joined_digits
- [Django]-Error: No module named staticfiles
- [Django]-How does one make logging color in Django/Google App Engine?
- [Django]-How do I filter ForeignKey choices in a Django ModelForm?
1π
import random
def get_random_hex:
random_number = random.randint(0,16777215)
# convert to hexadecimal
hex_number = str(hex(random_number))
# remove 0x and prepend '#'
return'#'+ hex_number[2:]
- [Django]-How to send a correct authorization header for basic authentication
- [Django]-Django :How to integrate Django Rest framework in an existing application?
- [Django]-What is the purpose of adding to INSTALLED_APPS in Django?
1π
Would like to improve upon this solution as I found that it could generate color codes that have less than 6 characters. I also wanted to generate a function that would create a list that can be used else where such as for clustering in matplotlib.
import random
def get_random_hex:
random_number = random.randint(0,16777215)
# convert to hexadecimal
hex_number = str(hex(random_number))
# remove 0x and prepend '#'
return'#'+ hex_number[2:]
My proposal is :
import numpy as np
def color_generator (no_colors):
colors = []
while len(colors) < no_colors:
random_number = np.random.randint(0,16777215)
hex_number = format(random_number, 'x')
if len(hex_number) == 6:
hex_number = '#'+ hex_number
colors.append (hex_number)
return colors
- [Django]-How to format time in django-rest-framework's serializer?
- [Django]-Embedding JSON objects in script tags
- [Django]-Django: OperationalError No Such Table
1π
Hereβs a simple code that I wrote based on what hexadecimal color notations represent:
import random
def getRandomCol():
r = hex(random.randrange(0, 255))[2:]
g = hex(random.randrange(0, 255))[2:]
b = hex(random.randrange(0, 255))[2:]
random_col = '#'+r+g+b
return random_col
The β#β in the hexadecimal color code just represents that the number represented is just a hexadecimal number. Whatβs important is the next 6 digits. Pairs of 2 digits in those 6 hexadecimal digits represent the intensity of RGB (Red, Green, and Blue) each. The intensity of each color ranges between 0-255 and a combination of different intensities of RGB produces different colors.
For example, in #ff00ff
, the first ff
is equivalent to 255 in decimal, the next 00
is equivalent to 0 in decimal, and the last ff
is equivalent to 255 in decimal. Therefore, #ff00ff
in hexadecimal color coding is equivalent to RGB(255, 0, 255)
.
With this concept, hereβs the explanation of my approach:
- Generated intensities of random numbers for each of
r
,g
andb
- Converted those intensities into hexadecimal
- Ignored the first 2 characters of each hexadecimal value
'0x'
- Concatenated
'#'
with the hexadecimal valuesr
,g
andb
intensities.
Feel free to refer to this link if you wanna know more about how colors work: https://hackernoon.com/hex-colors-how-do-they-work-d8cb935ac0f
Cheers!
- [Django]-How to get getting base_url in django template
- [Django]-Filter by property
- [Django]-"gettext()" vs "gettext_lazy()" in Django
- [Django]-Disabled field is not passed through β workaround needed
- [Django]-Django migration strategy for renaming a model and relationship fields
- [Django]-What is the equivalent of "none" in django templates?
1π
There are a lot of complex answers here, this is what I used for a code of mine using one import line and one line to get a random code:
import random as r
hex_color = '#' + ''.join([r.choice('0123456789ABCDEF') for _ in range(6)])
print(hex_color)
The output will be something like:
#3F67CD
If you want to make a list of color values, letβs say, of 10 random colors, you can do the following:
import random as r
num_colors = 10
hex_colors = ['#' + ''.join([r.choice('0123456789ABCDEF') for _ in range(6)]) for _ in range(num_colors)]
print(hex_colors)
And the output will be a list containing ten different random colors:
['#F13AB2', '#0F952F', '#DC0EFA', '#4ACD2A', '#61DD4A', '#CD53AF', '#8DF4F2', '#325038', '#6BC5EE', '#B90901']
I hope that helps!
- [Django]-In django do models have a default timestamp field?
- [Django]-How to assign items inside a Model object with Django?
- [Django]-How to change a django QueryDict to Python Dict?
0π
Hi, maybe i could help with the next function that generate random Hex colors :
from colour import Color
import random as random
def Hex_color():
L = '0123456789ABCDEF'
return Color('#'+ ''.join([random.choice(L) for i in range(6)][:]))
- [Django]-Django 2, python 3.4 cannot decode urlsafe_base64_decode(uidb64)
- [Django]-Django: How to check if the user left all fields blank (or to initial values)?
- [Django]-Can I access constants in settings.py from templates in Django?