A simple model ColorField that allows picking from a predefined list (currently picked up from settings.py
The widget displays as a row of coloured SPAN's with the hex code inside. Simply click to choose a color.
(requires jQuery in the page assigned to it's normal $ shortcut. Easy to change this is you don't use jQuery in this way)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | # settings.py
COLORPICKER_COLORS = [
'b4da35',
'37af68',
'64cf00',
'cfcc00',
'fdb735',
]
# customfields.py
from django import forms
from django.conf import settings
from django.db import models
from django.template.loader import render_to_string
class ColorWidget(forms.Widget):
def render(self, name, value, attrs=None):
colors = settings.COLORPICKER_COLORS
return render_to_string("color_widget.html", locals())
class ColorField(models.CharField):
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 10
super(ColorField, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
kwargs['widget'] = ColorWidget
return super(ColorField, self).formfield(**kwargs)
# templates/color_widget.html
<style>
.colorpicked {
border: 2px solid black;
}
span.colorpicker {
white-space: nowrap;
cursor: pointer;
}
span.colorpicker span {
padding: 5px;
}
</style>
<span id="colorpicker{{ attrs.id }}" class='colorpicker'>
{% for color in colors %}
<span data-color='{{ color }}' style="background-color: #{{ color }};" class="{% if color = value %}colorpicked{% endif %}">{{ color }}</span>
{% endfor %}
</span>
<input type="hidden" name="{{ name }}" value="{{ value }}" id="{{ attrs.id }}"/>
<script>
$(document).ready(function() {
$('#colorpicker{{ attrs.id }} span').bind('click', function() {
$('#{{ attrs.id }}').val(($(this).attr('data-color')));
$('#colorpicker{{ attrs.id }} span').removeClass('colorpicked');
$(this).addClass('colorpicked');
});
});
</script>
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
You can also extend it to give names to the colours.
First, make
COLORPICKER_COLORS
into a dictionary, something like this :Then , in
color_widget.html
, replace{% for color in colors %}
with{% for color, colname in colors.items %}
, and make the content of the span{{ colname }}
instead of{{ color }}
.#
Please login first before commenting.