使用HTML5输入类型'color

7 投票
2 回答
3012 浏览
提问于 2025-04-17 22:13

我有一个模型

# models.py
from django.db import models
    
class Foo(models.Model):
    # ...
    color = models.CharField(max_length=7, null=True)

color 应该用来存储一个十六进制颜色值。与其使用 input type="text",我想用 HTML5 的颜色输入框

我尝试通过设置以下表单对象来实现:

# forms.py
from django.forms import ModelForm, CharField

class FooForm(ModelForm):
    class Meta:
        model = Foo
        widgets = {
                   'color': CharField(attrs={'type': 'color'}),
                   }

但是,这给我带来了以下错误信息:

init() 收到了一个意外的关键字参数 'attrs'

我哪里做错了,应该怎么做才对呢?

2 个回答

1

如果你只是想更新 type 属性,你需要更新小部件的属性,而这个小部件是用于 文本输入框 的,适用于 字符字段

class FooForm(ModelForm):
    def __init__(self, *args, **kw):
        super(FooForm, self).__init__(*args, **kw)
        self.fields['color'].widget.attrs.update({
            'type': 'color',
        })

    class Meta:
        model = Foo
11

我自己解决了这个问题。它的工作方式几乎和我预想的一样:

# models.py
from django.db import models

class Foo(models.Model):
    # ...
    color = models.CharField(max_length=7, null=True)

# forms.py
from django.forms import ModelForm
from django.forms.widgets import TextInput

class FooForm(ModelForm):
    class Meta:
        model = Foo
        widgets = {
                   'color': TextInput(attrs={'type': 'color'}),
                   }

对我来说比较棘手的部分是不要忘记在视图里正确设置:

# views.py
from my_app.models import Foo
from my_app.forms import FooForm

class FooCreate(CreateView):
    model = Foo
    form_class = FooForm

感谢aamir-adnan - 他指出我应该使用TextInput,而不是CharField。

撰写回答