How to Display form field as dropdown.

I understand that invoking form in the front end template will automatically render all the fields as expected. It gets better if I make it a crispy form. I really don’t get my desired styling using the above method so I decided to specifically use the name to field style. Everything seems to work well, but I have an issue with how to display the contents on the dropdown list. Pls, how can I achieve this?

forms.py

class InsuranceQuoteForm(forms.ModelForm):

    class Meta:

        model = InsuranceQuote

        fields = ("employment_status","age_range")

        widgets = {

            'employment_status': ChoiceField(choices=employment_choice),

            'age_range': ChoiceField(choices=age_range),

        }

views.py

def quote_form(request):

    if request.method == 'POST':

        form = InsuranceQuoteForm(request.POST or None)

        if form.is_valid():

            employment_status = form.cleaned_data.get("employment_status")

            age_range = form.cleaned_data.get('age_range')

            form.save()

            # redirect with the success message

            messages.success(request, 'Quote sent successfully',

                             extra_tags='success')

            return redirect(to='/')

        else:

            return messages.error(request, 'An unexpected error has occured.',

                                  extra_tags='error')

    form = InsuranceQuoteForm()

    template = 'homequote.html'

    context = {

        'quote_form': form,

    }

    return render(request, template, context)

homequote.html


<div class="col-lg-6 col-sm-6">

      <div class="form-group">

           <select name="insure_name">

               <option value="1">Insurance Type</option>

                   **{% for k,x in employment_status%}

                      <option value="{{k.keys}}">{{x.values}}</option>

                    {% endfor %}  **//Don't really get how to use the key and the value.

                 </select>

       </div>

    </div>

There are ways to appropriate address those issues through both the form and the template.

What do you mean by this?

{{ quote_form.employment_status }} renders both the select box and the appropriate options.

1 Like

Thanks so much @KenWhitesell based on your comments, I’m able to achieve something similar to my expected solution by performing some loop on field|as_crispy_field.