1

I have something like this:

class MyForm(forms.Form):

    CHOICES = (
        ('opt1', 'Opt1'),
        ('group',(
            ('opt2', 'Opt2'),
            ('opt3', 'Opt3'),
            )
        ),
    )   
    
    myfield = forms.ChoiceField(choices=CHOICES, required=False)

when i render this form, opt1 is selected by default, But I need opt3 to be the selected one.

i tried something like:

myfield = forms.ChoiceField(choices=CHOICES, required=False, initial="opt3")

but it didnt work.

what i get:

<select name="myfield" id="id_myfield">
    <option value="opt1">Opt1</option>
    <optgroup label="group">
        <option value="opt2">Opt2</option>
        <option value="opt3">Opt3</option>
    </optgroup>
</select>

what im trying to get:

<select name="myfield" id="id_myfield">
    <option value="opt1">Opt1</option>
    <optgroup label="group">
        <option value="opt2">Opt2</option>
        <option value="opt3" selected>Opt3</option>
    </optgroup>
</select>

How can i get opt3 selected by default?

Brahim
  • 67
  • 1
  • 7
  • 1
    https://stackoverflow.com/questions/657607/setting-the-selected-value-on-a-django-forms-choicefield this should work – Gilbish Kosma Sep 17 '20 at 16:53
  • Now it work, it didnt work before because in my view i had MyForm(request.GET) to complete with the data filled by the user. Then the initial data is ignored. I made it work with an if sentence asking for request.GET, then MyForm(request.GET) or MyForm() according to the case. – Brahim Sep 17 '20 at 17:37

1 Answers1

0

its work

myfield = forms.ChoiceField(choices=CHOICES, required=False, initial="opt3`")

my problem was my view:

form = MyForm(request.GET)

now i solve the problem with:

if request.GET:
    form = MyForm(request.GET)
else:
    form = MyForm()
Brahim
  • 67
  • 1
  • 7