Ask Your Question

How to dynamically update the 'initial' value in a Form ChoiceField

asked 2015-01-23 10:15:15 -0500

eugene.goldberg gravatar image

updated 2015-01-23 13:54:55 -0500

rbowen gravatar image

I have a Form with the following field:

image_choices = []
    images = forms.ChoiceField(label=_("Images"), choices=image_choices, initial="")

I need to be able to update the value of the 'initial' attribute, after I learn what that value should be. Currently, I have this assignment done within the __init__ :

def __init__(self, request, image_choices=image_choices, flavor_choices=flavor_choices,
                 *args, **kwargs):
        super(UpdateWorkload, self).__init__(request, *args, **kwargs)
       selected_image = selected_workload['image']
      self.fields['images'].initial = str(selected_image)

I do not get any errors, and, when printed, the value is there, but, in the actual form on the screen, I still get my default list, and no specific items are selected, as per self.fields['images'].initial = str(selected_image)

How can I fix that?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2015-01-25 09:06:18 -0500

eugene.goldberg gravatar image

As it turns out, this was the actually correct syntax:

class UpdateWorkload(forms.SelfHandlingForm): name = forms.CharField(max_length="255", label=_("Workload Name")) description = forms.CharField(widget=forms.Textarea, label=_("Description"), required=False) image_choices = [] images = forms.ChoiceField(label=_("Images"), choices=image_choices) flavor_choices = [] flavors = forms.ChoiceField(label=_("Flavors"), choices=flavor_choices)

def __init__(self, request, image_choices=image_choices, flavor_choices=flavor_choices,
             *args, **kwargs):
    super(UpdateWorkload, self).__init__(request, *args, **kwargs)

    images, self._more, self._prev = api.glance.image_list_detailed(
    flavors = api.nova.flavor_list(request, True)

    for image in images:
    if len(image_choices) > 1:
        image_choices.insert(0, ('', _("Select an Image")))
    self.fields['images'].choices = image_choices

    for flavor in flavors:
    if len(flavor_choices) > 1:
        flavor_choices.insert(0, ('', _("Select an Flavor")))
    self.fields['flavors'].choices = flavor_choices
    selected_workload = kwargs['initial']
    selected_image = selected_workload['image']
    selected_flavor = selected_workload['flavor']

    self.fields['images'].initial = selected_image
    self.fields['flavors'].initial = selected_flavor
edit flag offensive delete link more

Get to know Ask OpenStack

Resources for moderators

Question Tools

1 follower


Asked: 2015-01-23 10:15:15 -0500

Seen: 544 times

Last updated: Jan 25 '15