Elisa
Elisa

Reputation: 7093

Choice field initial data

I have form like below. How can I get a value selected?

class ProfileForm(forms.Form):

name = forms.CharField(label=_('Full Name'))
about = forms.CharField(widget=forms.Textarea(), label=_('Tell something about you'))
country = forms.CharField(label=_('Country'), required=False)

def __init__(self, tz_choice=0, *args, **kwargs):
    super(ProfileForm, self).__init__(*args, **kwargs)

    country_list = Country.objects.all().order_by('name')

    country_opt = [('', _('Select'))]
    for ct in country_list:
        country_opt.append([ct.country_code, ct.name])

    self.fields['country'] = forms.ChoiceField(choices=country_opt, initial='NP')

In above example, I want Nepal to be selected.

Upvotes: 1

Views: 2786

Answers (1)

mossplix
mossplix

Reputation: 3865

You can try using ModelChoiceField

class ProfileForm(forms.Form):

   name = forms.CharField(label=_('Full Name'))
   about = forms.CharField(widget=forms.Textarea(), label=_('Tell something about you'))
   country = forms.ModelChoiceField(label=_('Country'), queryset=Country.objects.all(), required=False,initial=Country.objects.get(code="np").pk)  

Upvotes: 2

Related Questions