Django表单错误 '获得多个值用于关键字参数'choices

3 投票
1 回答
3358 浏览
提问于 2025-04-16 16:50

在定义我的Django表单时遇到了一个奇怪的错误。我收到的错误信息是:

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

这个问题出现在TestForm和SpeciesForm上(下面有引用);基本上就是这两个表单都有一个叫'choices'的参数。init()这个方法从来没有被明确调用过,而且这些表单在视图中还没有被实例化。这里有一个ModelForm和一个普通的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

任何帮助都非常感谢。我不太明白为什么会出现这个问题,因为这些表单的内容非常简单。

1 个回答

7

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

这是一个可迭代的对象(比如列表或元组),包含 二元组,用作这个字段的选择。这个参数接受与 模型字段的 choices 参数相同的格式。有关 选择的更多细节,请参见模型字段的 参考文档。

撰写回答