bbrooke
bbrooke

Reputation: 2347

Display "Choose Option" label in Django ModelForm ChoiceField

I have a Django ModelForm ChoiceField and would like to display the text "Choose option" in the dropdown when user visits page. ("Choose option" wouldn't be an actual "value" rather just a "label")

Any thoughts how I can add this to my code below?

I appreciate the time.

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)

Upvotes: 1

Views: 2076

Answers (2)

Maksym Potapchuk
Maksym Potapchuk

Reputation: 1

Try empty_label="Choose option" in your forms.py:

class UserForm(forms.Form):
    brand = forms.ModelChoiceField(
        queryset=Brands.objects.all(), required=False, empty_label="Brands"
    )

Upvotes: 0

arocks
arocks

Reputation: 2882

Just use the label argument, like:

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

Or if you would like it present inside the dropdown without being an actual choice then insert it as the first 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)

Upvotes: 2

Related Questions