【问题标题】:Django forms error 'got multiple values for keyword argument 'choices''Django 表单错误'为关键字参数'选择'获取了多个值'
【发布时间】:2011-05-02 18:44:00
【问题描述】:

定义我的 django 表单时出现一个奇怪的错误。我得到了错误:

__init__() got multiple values for keyword argument 'choices'

TestForm 和 SpeciesForm 都会发生这种情况(引用如下);基本上这两种形式都带有“选择”关键字参数。 init() 从未显式调用,并且表单甚至还没有在视图中实例化。有一个 ModelForm 和一个 plain Form。

from django import forms as f
from orders.models import *

class TestForm(f.Form):
    species = f.ChoiceField('Species', choices=Specimen.SPECIES)
    tests = f.MultipleChoiceField('Test', choices=Test.TESTS, widget=f.CheckboxSelectMultiple())
    dna_extraction = f.CharField('DNA extraction', help_text='If sending pre-extracted DNA, we require at least 900 ng')

class SpeciesForm(f.ModelForm):
    TYPE_CHOICES = (
        ('blood', 'Blood'),
        ('dna', 'Extracted DNA'),
    )
    dam_provided = f.BooleanField('DAM', help_text='Is dam for this specimen included in sample shipment?')
    sample_type = f.ChoiceField('Type of sample', choices=TYPE_CHOICES)
    dna_concentration = f.CharField('DNA concentration', help_text='If sending extracted DNA, approximate concentration')

    class Meta:
        exclude = ['order']
        model = Specimen

任何帮助将不胜感激。不知道为什么会发生这种情况,因为表单非常简单。

【问题讨论】:

  • 回溯不仅仅是随机噪声,你知道:它包含有用的调试信息。请张贴。
  • @Daniel Roseman:+1。你的评论让我崩溃了。
  • 这很奇怪。我可以始终如一地重现它,但似乎找不到解决方法。确实很奇怪!

标签: python django forms


【解决方案1】:

http://code.djangoproject.com/browser/django/trunk/django/forms/fields.py#L647

647     def __init__(self, choices=(), required=True, widget=None, label=None,
648                  initial=None, help_text=None, *args, **kwargs):
649         super(ChoiceField, self).__init__(required=required, widget=widget, label=label,
650                                         initial=initial, help_text=help_text, *args, **kwargs)

使用:

species = f.ChoiceField(label='Species', choices=Specimen.SPECIES)
tests = f.MultipleChoiceField(label='Test', choices=Test.TESTS, widget=f.CheckboxSelectMultiple())

和:

sample_type = f.ChoiceField(label='Type of sample', choices=TYPE_CHOICES)

这是假设您的选择是有效的。不确定 Specimen.SPECIES 和 Test.TESTS 是什么。这些应该是可迭代的两个元组,根据:

ChoiceField.choices

一个可迭代的(例如,一个列表或元组) 用作此选项的 2 元组 场地。这个论点接受相同的 格式作为 a 的选择参数 模型字段。查看模型字段 关于选择的参考文档 更多细节。

【讨论】:

  • 谢谢!我认为这个问题突出了表单字段(以及模型与表单在一定程度上)的一些可用性问题。直觉上,我假设我可以像给任何其他表单字段一样给这些标签贴上标签。
猜你喜欢
  • 2012-11-12
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多