在表单django

时间:2017-06-22 09:11:23

标签: django colors field

我正在尝试添加colorField; https://djangosnippets.org/snippets/1261/

我将这些添加到我的models.py,

class ColorField(models.CharField):
    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 10
        super(ColorField, self).__init__(*args, **kwargs)

    def formfield(self, **kwargs):
        kwargs['widget'] = ColorPickerWidget
        return super(ColorField, self).formfield(**kwargs)

现在在我的forms.py中,我正在尝试使用formField方法,(我正在使用form.Form表单而不是FormModel)
但是这样做:

star_color = ColorField.formfield(ColorField) 

我不断收到错误:必须使用ColorField实例作为第一个参数调用未绑定的方法formfield()(获取类型实例instea)??

3 个答案:

答案 0 :(得分:0)

我不确定你为什么要使用这种语法。

该代码显示ColorField没有特定的表单字段;只是一个小部件。您应该直接使用小部件:

star_color = forms.CharField(widget=ColorPickerWidget)

答案 1 :(得分:0)

这个片段并不是真的适合你的用例,你只需要一个带有ColorPickerWidget的forms.CharField,而不是一个模型ColorField作为formfield

class YourForm(forms.Form):
    star_color = forms.CharField(widget=ColorPickerWidget)

答案 2 :(得分:0)

我不知道这是否仍然相关,但您可以切换到 ModelForm 实例并使用 html 类型颜色:

forms.py

from django.forms import ModelForm
from django.forms.widgets import TextInput
from .models import Website


class ColorPickerForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(ColorPickerForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.fields["primary_color"].widget = TextInput(
                attrs={"type": "color", "title": self.instance.primary_color}
            )
            self.fields["secondary_color"].widget = TextInput(
                attrs={"type": "color", "title": self.instance.secondary_color}
            )

    class Meta:
        model = Website
        fields = "__all__"
        widgets = {
            "primary_color": TextInput(attrs={"type": "color"}),
            "secondary_color": TextInput(attrs={"type": "color"}),
        }

models.py

from django.db import models

class Website(models.Model):
    ...
    primary_color = models.CharField(max_length=7, default="#023458")
    secondary_color = models.CharField(max_length=7, default="#ffffff")

forms.py 文件中的 init 函数仅用于将标题属性设置为所选颜色值。当您想在不点击颜色选择器的情况下查看十六进制代码时,有时会很有帮助。