Custom color field with Javascript color picker

 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. models ColorField with clean minimal widget by andybak 2 years ago
  2. HTML Hex Color Field by claudelacey 4 years ago
  3. jQuery color picker model field by fneumann 4 years, 5 months ago
  4. Django admin inline ordering - javascript only implementation by ojhilt 5 months, 3 weeks ago
  5. Unobtrusvie Foldable Admin Interface by whiteinge 5 years, 4 months ago

Comments

Natim (on August 6, 2009):

J'ai amélioré le JS de ColorPicker pour #django. http://paste.pocoo.org/show/132858/

#

gamesbook (on March 2, 2010):

See:

http://www.mkyong.com/regular-expressions/how-to-validate-hex-color-code-with-regular-expression/

#

TAMRALuna (on August 21, 2011):

If you want to buy a house, you would have to get the home loans. Moreover, my father all the time takes a financial loan, which is really rapid.

#

(Forgotten your password?)