Login

Custom color field with Javascript color picker

Author:
seanl
Posted:
July 21, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

A custom model field 'ColorField' which stores a hex color value like '#FFFFFF' and shows a Javascript color picker in the admin rather than a raw text field. It is written to work with the current trunk (i.e. after newforms-admin merge).

You'll need the ColorPicker2.js file found at www.mattkruse.com (his license prohibits including the file here). This should be placed in the 'js' folder of your admin media.

The snippet includes a python source file which can be placed wherever you wish, and a template which by default should be placed in a folder 'widget' somewhere on your template path. You can put it elsewhere, just update the path ColorWidget.render

The custom field at present does not validate that the text is a valid hex color value, that'd be a nice addition.

 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
# 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):
    class Media:
        js = [settings.ADMIN_MEDIA_PREFIX + "js/ColorPicker2.js"]
        
    def render(self, name, value, attrs=None):
        return render_to_string("widget/color.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/widget/color.html

{% load common %}
<script type="text/javascript" charset="utf-8">
  var picker_{{ name }} = new ColorPicker('window');
</script>
<input type="text" readonly="true" tabindex="-1" size="2" style="background-color: {{ value }};" id="{{ attrs.id }}-sample"/>
<input type="text" name="{{ name }}" size="8" value="{{ value }}" id="{{ attrs.id }}" onChange="alert('changed');"/>
<a href="#" onclick="picker_{{ name }}.select(document.getElementById('{{ attrs.id }}'),document.getElementById('{{ attrs.id }}-sample'),'{{ attrs.id }}-pick');return false;" name="{{ attrs.id }}-pick" id="{{ attrs.id }}-pick">Pick</a>
<script type="text/javascript" charset="utf-8">
  picker_{{ name }}.writeDiv();
</script>

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.