在Django ModelForm ChoiceField中显示“选择选项”标签

时间:2014-01-31 18:32:00

标签: django django-forms

我有一个Django ModelForm ChoiceField,并希望在用户访问页面时在下拉列表中显示“选择选项”文本。 (“选择选项”不是实际的“值”而只是“标签”)

我是否可以将其添加到下面的代码中?

我很感激时间。

class ExerciseForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(ExerciseForm, self).__init__(*args, **kwargs)

        exercises = Exercise.objects.all().order_by('name')
        exercise_choices = [(exercise.youtube_id, exercise.name) for exercise in exercises]
        self.fields['exercise'] = forms.ChoiceField(choices=exercise_choices)

1 个答案:

答案 0 :(得分:1)

只需使用label argument,例如:

self.fields['exercise'] = forms.ChoiceField(choices=exercise_choices, label="Choose option")

或者如果您希望它在下拉列表中显示而不是实际选择,那么将其作为第一个选项插入:

exercises = Exercise.objects.all().order_by('name')
exercise_choices = [(exercise.youtube_id, exercise.name) for exercise in exercises]
exercise_choices.insert(0, (u"", u"Choose option"))
self.fields['exercise'] = forms.ChoiceField(choices=exercise_choices)