Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot set initial value for forms.ChoiceField in django

everyone

I want to set initial value for ChoiceField while that value isn't in choices of ChoiceField

following is the ArticleForm definition:

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

then I instantiated the form by passing the initial argument:

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

notice that the initial value('Portrush') isn't one of choices defined in ChoiceField('a' and 'b')

How could I set initial value? Any suggestion is appreciated.

like image 289
Mark Ma Avatar asked Jul 13 '11 02:07

Mark Ma


1 Answers

May be something like this:

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>'
like image 190
sacabuche Avatar answered Oct 22 '22 08:10

sacabuche