我正在尝试在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')
}),
)
但是,该字段的类型仍为文本。如何在管理页面中将输入字段的类型更改为颜色?
答案 0 :(得分:20)
我在文档中找到了答案:
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')
}),
)
答案 1 :(得分:0)
您可以使用此库 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')
答案 2 :(得分:0)
如果您要向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
。