Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Preselect options in MultipleChoiceField

I have a class form that has the forms.MultipleChoiceField in it.

I am able to render it and show all the choices to select / highlight, but what I want is the choices that get displayed to be pre-highlighted. so it is up to the user to either deselect the options or leave them as they are when they submit the form.

Is there a way to do this ?

Thanks

like image 516
Jason Pope Avatar asked Jan 25 '26 05:01

Jason Pope


1 Answers

You only need to set initial values to your field like this:

class YourForm(forms.Form):
    choices = (
          ('choice1':'choice1'),
          ('choice2':'choice2'),
          ('choice3':'choice3')
           )
   #for example if you want to select choice1 and choice2
   initial_values = ['choice1', 'choice2']
   field = forms.MultipleChoiceField(initial=initial_values)
like image 81
Messaoud Zahi Avatar answered Jan 26 '26 19:01

Messaoud Zahi