python - 无法在 django 中为 forms.ChoiceField 设置初始值

标签 python django django-forms

大家

我想为 ChoiceField 设置初始值,而该值不在 ChoiceField 的选择中

以下是 ArticleForm 定义:

def ArticleForm(forms.Form):
  choice = forms.ChoiceField(choices=[['a':'a'],['b':'b']])

然后我通过传递初始参数来实例化表单:

form = ArticleForm(initial={'choice':'Portrush'})

请注意初始值('Portrush')不是 ChoiceField('a' 和 'b')中定义的选项之一

如何设置初始值?任何建议表示赞赏。

最佳答案

可能是这样的:

class ArticleForm(forms.Form):
    LETTER_A = 'a'
    LETTER_B = 'b'
    # look not a dict
    CHOICES = ((LETTER_A,'letter a'),
               (LETTER_B,'letter b'))

    choice = forms.ChoiceField(choices=CHOICES)

    def __init__(self, *args, **kwargs):
        initial =  kwargs.get('initial', {})
        choice = initial.get('choice', None)

        # set just the initial value
        # in the real form needs something like this {'choice':'a'}
        # but in this case you want {'choice':('a', 'letter_a')}
        if choice:
            kwargs['initial']['choice'] = choice[0]

        # create the form
        super(ArticleForm, self).__init__(*args, **kwargs)

        # self.fields only exist after, so a double validation is needed
        if  choice and choice[0] not in (c[0] for c in self.CHOICES):
            self.fields['choice'].choices.append(choice)


form = ArticleForm(initial={'choice':('c','other')})
form.as_p()
>>> u'<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">\n<option value="a">letter a</option>\n<option value="b">letter b</option>\n<option value="c" selected="selected">other</option>\n</select></p>'

关于python - 无法在 django 中为 forms.ChoiceField 设置初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6673308/

相关文章:

python - 为什么 timedeltas 不能在 NumPy 中进行乘法/除法?

python - Django:如何使用自定义模板制作表单?

python - Hook 到 django 字段分配

python - Django 1.9 在两个页面形式中使用 django session

python - 使用 dpkt 的微秒分辨率

python - 在 IronPython 2.7 和 Python3.5 中压缩

Python Django 如何在 django models.py 中创建哈希字段

Django:允许用户在表单字段中提交有效的HTML

python - Django RadioSelect 从模型中选择

python - Django导入/导出: ForeignKey fields return None