How to use HTML5 color picker in Django admin

I am trying to implement HTML5 colorpicker on the admin page on Django.

Here is my model:

#model.py ... class Category(models.Model): ... color = models.CharField(max_length=7) 

Here is the form:

 #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'}), } class CategoryAdminForm(ModelForm): form = CategoryForm 

And finally, the administrator:

 #admin.py ... from .forms import CategoryAdminForm ... class CategoryAdmin(admin.ModelAdmin): form_class = CategoryAdminForm filter_horizontal = ('questions',) fieldsets = ( (None, { 'fields': (('name', 'letter'), 'questions', 'color') }), ) 

However, the field type is still text. How to change input field type for color on admin page?

+8
source share
2 answers

I found the answer in the documentation:

Extra class in forms.py not needed

 #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 admin:

 #admin.py ... from .forms import CategoryForm ... class CategoryAdmin(admin.ModelAdmin): form = CategoryForm filter_horizontal = ('questions',) fieldsets = ( (None, { 'fields': (('name', 'letter'), 'questions', 'color') }), ) 
+21
source

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

Installation:

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

Using:

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') 
0
source

All Articles