[Django]-How to use HTML5 color picker in Django admin

45πŸ‘

I found the answer in the documentation:

The extra class in forms.py was not necessary

#form.py
from django.forms import ModelForm
from django.forms.widgets import TextInput
from .models import Category

class CategoryForm(ModelForm):
    class Meta:
        model = Category
        fields = '__all__'
        widgets = {
            'color': TextInput(attrs={'type': 'color'}),
        }

And in the admin:

#admin.py
...
from .forms import CategoryForm

...
class CategoryAdmin(admin.ModelAdmin):
    form = CategoryForm
    filter_horizontal = ('questions',)
    fieldsets = (
        (None, {
            'fields': (('name', 'letter'), 'questions', 'color')
            }),
        )
πŸ‘€shefHauwanga

15πŸ‘

You can use this library
https://github.com/jaredly/django-colorfield

Installation:

  • Run pip install django-colorfield
  • Add colorfield to your INSTALLED_APPS
  • Collect static files with ./manage.py collectstatic

Usage:

In your models, you can use it like this:

from django.db import models
from colorfield.fields import ColorField

class MyModel(model.Model):

     color = ColorField(default='#FF0000')

3πŸ‘

If you want to add a color picker to a forms.Form rather than a model.Model this would be the way to go:

from django import forms

class GaeParamsForm(forms.Form):
    hex_color = forms.CharField(label='hex_color', max_length=7,
        widget=forms.TextInput(attrs={'type': 'color'}))
    font_size = forms.IntegerField(label='font_size', 
        min_value=1, max_value=400)

This essentially writes the type attribute of the input HTML tag, i.e.

<input id="id_hex_color" maxlength="7" name="hex_color" type="color">

You will receive the data as hex string with # sign e.g. #ff0000.

πŸ‘€xjcl

Leave a comment