简体   繁体   中英

Pre-populate Django form ChoiceField with instance data

Help needed with pre-populating Django forms: I have a form that updates a UserProfile model, when the form is loaded I want it pre-populated with the existing UserProfile data. Simple enough, the instance can be passed to the form. However, it seems that fields with choices (which come out as select drop-down elements in HTML) are not pre-populated with the instance data and instead default to '-----------'.

I've tried manually setting the initial value for a specific form (eg country) but it doesn't pull through to the HTML.

    form = UserProfileForm(instance=user_profile)
    form.fields['country'].initial = 'GBR'

I'm sure I could create a convoluted work around to get the current country selected in the front-end but it feels like it should be possible in Django. I couldn't see any solutions in other questions.

You can dynamically set default for a form field as:

form = UserProfileForm(instance=user_profile, initial={'country': 'GBR'})

If country field should be populated from user_profile data, then you can define form as following (assuming country is a field in UserProfile class)

class UserProfileForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        if self.instance:
            self.initial['country'] = instance.country

Why what you are doing isn't working?

You are using:

form.fields['country'].initial = 'GBR'

This will not work on for a bounded form . form = UserProfileForm(instance=user_profile) will return a bounded form.

Fromdocs :

The initial argument lets you specify the initial value to use when rendering this Field in an unbound Form .

To specify dynamic initial data, see the Form.initial parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM