Reputation: 851
I'm trying to implement the HTML5 colorpicker in Django's admin page.
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 admin:
#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 type for the field is still text. How do I change the type for the input field to color in the admin page?
Upvotes: 24
Views: 27657
Reputation: 327
Create an input widget for the color field by subclassing the django Input widget.
from django.forms import ModelForm
from django.forms.widgets import TextInput
from .models import Category
# color input field
class ColorInput(forms.widgets.Input):
input_type = "color"
class CategoryForm(ModelForm):
class Meta:
model = Category
fields = '__all__'
widgets = {
'color': ColorInput(),
}
Upvotes: 0
Reputation: 15329
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
.
Upvotes: 3
Reputation: 169
You can use this library https://github.com/jaredly/django-colorfield
Installation:
pip install django-colorfield
colorfield
to your INSTALLED_APPS
./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')
Upvotes: 16
Reputation: 851
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')
}),
)
Upvotes: 48