python - 子类化 django choicefield 不起作用

标签 python django subclass choicefield

我正在尝试对 ChoiceField 进行子类化,以便我可以以多种形式使用它(DRY)。例如:

class testField(forms.ChoiceField):
  choices = (('a', 'b'), ('c', 'd'))
  label = "test"

class testForm(forms.Form):
  test = testField()

其他类型的字段作为子类工作(例如 CharField),但是在渲染 ChoiceField 的子类时,我收到一个模糊的错误:

AttributeError at /..url.../
'testField' object has no attribute '_choices'

在子类中指定choices_choices不会报错,但渲染中也不会显示内容。

最佳答案

不要弄乱 Field 的类属性,choicesChoiceField 实例的属性。按照 docs 中的建议,重写 __init__(...) :

class TestField(ChoiceField):
    def __init__(self, *args, **kwargs):
        kwargs['choices'] = ((1, 'a'), (2, 'b'))
        kwargs['label'] = "test"
        super(TestField, self).__init__(*args, **kwargs)

class TestForm(Form):
    test = TestField()

f = TestForm()

f.fields['test'].choices
> [(1, 'a'), (2, 'b')]

f.fields['test'].label
> 'test'

关于python - 子类化 django choicefield 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36821980/

相关文章:

django - celery celerybeat 不滴答作响

python - 检查 python 中浮点列的相等性

python - ctypes找不到find dll函数

python - 如果我不提供任何静态内容,我是否需要 Nginx 和 Gunicorn?

JavaScript 原型(prototype)设计 : single prototype object or not?

javascript - jquery如何返回被选元素的数组

iOS 9 Swift UIButton CheckBox 子类不显示图像

python - 为什么我不能打印堆队列?

python - 如何阻止 PyCharm 在格式化代码时插入空格以进行精确对齐?

python - SQLAlchemy 等同于 Django 的 annotate() 方法