models ColorField with clean minimal widget

 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

  1. CitySelector by JustDelight 2 years, 2 months ago
  2. jQuery color picker model field by fneumann 5 years, 4 months ago
  3. Autocomplete TextInput Widget w/ Static Data (jQuery UI) by JoeLinux 1 year, 1 month ago
  4. jQuery Autocomplete by zeeg 6 years, 10 months ago
  5. Bootstrap button dropdown widget (replaces forms.Select) by benjaoming 1 year, 8 months ago

Comments

badrihippo (on August 30, 2013):

You can also extend it to give names to the colours.

First, make COLORPICKER_COLORS into a dictionary, something like this :

COLORPICKER_COLORS = {
    'ff0000': 'red',
    '00ff00': 'green',
    '0000ff': 'blue',
    'ffffff': 'white',
    '000000': 'black'
}

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 }}.

#

(Forgotten your password?)