简体   繁体   中英

Django Dynamically add choices to choicefield form

I would like to dynamically add choices to the form from data pulled in views.py. this list will change frequently so I can't hard code this.

I'm running a query against the AWS API, and pulling down backups. I am trying to get these backups in a list then get these in a dropdown to submit in a form.

forms.py

class RestoreAMIForm(forms.ModelForm):
ami = forms.ChoiceField()
def __init__(self, *args, **kwargs):
    super(RestoreAMIForm, self).__init__(*args, **kwargs)
    self.fields['server_name'].widget.attrs['readonly'] = True
    self.fields['module_name'].widget.attrs['readonly'] = True
    self.fields['instance_id'].widget.attrs['readonly'] = True
class Meta:
    model = RestoreRequest
    fields = ['server_name', 'module_name', 'instance_id', 'ami', 'justification']

views.py

    amis = helper_functions.get_all_backups(instance_id, GlobalrunEnv)
    context['ami'] = amis
    just_amis = [i[0] for i in context['ami']]
    formatted_picker = helper_functions.iterate_over_list(just_amis)
    context['restore_ami_form'] = RestoreAMIForm(initial={'server_name': context['tags']['Name'],
                                                                  'instance_id': context['server_details']['InstanceId'],
                                                                  'module_name': context['passed_slug'],
                                                                  'ami': formatted_picker, })

html

        <form action="{% url 'instance_details' passed_slug %}" method="post">
        <p class="standout"> Revert to Snapshot:</p>
        <table>
            {{ restore_ami_form.as_table }}
        </table>
        <div class="buttonHolder">
        <button name="RevertRequest" value="{{ GlobalrunEnv }}">Submit New Values</button>
        </div>
    </form>

the output of format_picker is...

[('1', 'ami-04e05d8b305348d89'), ('2', 'ami-0f82b7ac27bdeb246'), ('3', 'ami-0eed0d484f0d61391'), ('4', 'ami-071cfbc9eda4cae4d'), ('5', 'ami-0dc61e733721e7e7a'), ('6', 'ami-05ba2995c14da2502'), ('7', 'ami-01cb5e766d77f8ecb')]

my read only fields are working. Is is possible to provide initial= values for choice fields?

Anyone curious I ended up finding a way to accomplish this. I modified the init of the form to accept "internal choices". Then when creating the form on views.py I pass this this before the initial kwargs.

This did cause a slight issue later since i'm unable to directly reference the values for the options, but I got around this by using...

request.session['archived_amis'] = formatted_picker

then in the post doing ami_choices = request.session.get('archived_amis', None)

changes below

views.py

    formatted_picker = helper_functions.iterate_over_list(just_amis)
    """This data needs to be saved to reference later in the post, in the off chance that the data changes between
    initially loading the variable and submitting the form"""
    request.session['archived_amis'] = formatted_picker
    context['restore_ami_form'] = RestoreAMIForm(formatted_picker, initial={'server_name': context['tags']['Name'],
                                                          'instance_id': context['server_details']['InstanceId'],
                                                          'module_name': context['passed_slug'], })

forms.py

class RestoreAMIForm(forms.ModelForm):
# ami = forms.ChoiceField()
def __init__(self, internal_choices, *args, **kwargs):
    super(RestoreAMIForm, self).__init__(*args, **kwargs)
    self.fields['server_name'].widget.attrs['readonly'] = True
    self.fields['module_name'].widget.attrs['readonly'] = True
    self.fields['instance_id'].widget.attrs['readonly'] = True
    self.fields['ami'] = forms.ChoiceField(label='AMI', required=True, choices=internal_choices)
class Meta:
    model = RestoreRequest
    fields = ['server_name', 'module_name', 'instance_id', 'ami', 'justification']

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