我正在尝试在 Django 的管理页面中实现 HTML5 颜色选择器。
这是我的模型:
#model.py
...
class Category(models.Model):
...
color = models.CharField(max_length=7)
表格如下:
#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
最后是管理员:
#admin.py
...
from .forms import CategoryAdminForm
...
class CategoryAdmin(admin.ModelAdmin):
form_class = CategoryAdminForm
filter_horizontal = ('questions',)
fieldsets = (
(None, {
'fields': (('name', 'letter'), 'questions', 'color')
}),
)
但是,该字段的类型仍然是文本。如何在管理页面中将输入字段的类型更改为颜色?
我在文档中找到了答案:
forms.py中的额外类是没有必要的
#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'}),
}
在管理员中:
#admin.py
...
from .forms import CategoryForm
...
class CategoryAdmin(admin.ModelAdmin):
form = CategoryForm
filter_horizontal = ('questions',)
fieldsets = (
(None, {
'fields': (('name', 'letter'), 'questions', 'color')
}),
)
您可以使用这个库 https://github.com/jaredly/django-colorfield
安装:
pip install django-colorfield
colorfield
添加到您的 INSTALLED_APPS
./manage.py collectstatic
用途:
在你的模型中,你可以这样使用它:
from django.db import models
from colorfield.fields import ColorField
class MyModel(model.Model):
color = ColorField(default='#FF0000')
如果您想将颜色选择器添加到
forms.Form
而不是 model.Model
,这将是要走的路:
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)
这本质上是写入输入 HTML 标签的 type 属性,即
<input id="id_hex_color" maxlength="7" name="hex_color" type="color">
您将收到带 # 符号的十六进制字符串数据,例如
#ff0000
。
通过子类化 django 输入小部件,为颜色字段创建一个输入小部件。
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(),
}