如何在Django admin

时间:2016-10-04 18:21:26

标签: python django html5

我正在尝试在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')
            }),
        )

但是,该字段的类型仍为文本。如何在管理页面中将输入字段的类型更改为颜色?

3 个答案:

答案 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