rockyl
rockyl

Reputation: 133

Django - Getting form field by string var

i'm trying to get an form with Django displaying properly. My form has multiple segments, and one group looks like this:

aant_inw = forms.BooleanField(widget=forms.HiddenInput(), required=True, label="Aantal inwoners")
aant_inw_min = forms.IntegerField(required=False)
aant_inw_max = forms.IntegerField(required=False) 
aant_inw_priority = forms.FloatField(required=False)   

The problem is that I only loop over the hidden fields, then in that row I want to add the 3 other (once this one is checked, the other 3 form fields for that group turn visible).

I thought about creating a var that stores the string to the correct field in the form. So adding _min, _max, _priority to the original html_name as a prefix. I'm not really sure how to this though. I tried using my var to get the correct form in multiple ways. I tried form.fieldname, form[fieldname], and form.{{fieldname}}. But none of these seem to work and return aboolutely nothing. Below is a little snippet of what I'm trying to do.

{% with fieldname=field.html_name|add:'_min' %}
      <tr class="collapse" id="{{ field.html_name }}">
             <td>{{ field.label }}</td>
             <td>{% render_field form.{{fieldname}} class+="form-control" %}</td>
             <td>{% render_field form.fieldname class+="form-control" %}</td>
      </tr>
{% endwith %}

I hope someone can help me out with this!

Upvotes: 0

Views: 550

Answers (1)

MikeVelazco
MikeVelazco

Reputation: 905

My option is not pretty, but it must work:

{% with fieldname=field.html_name|add:'_min' %}
  <tr class="collapse" id="{{ field.html_name }}">
         <td>{{ field.label }}</td>
         {% if fieldname == "aant_inw_min" %}
         <td>{% render_field form.aant_inw_min class+="form-control" %}</td>
         {% elif fieldname == "aant_inw_max" %}
         <td>{% render_field form.aant_inw_max class+="form-control" %}</td>
         {% elif fieldname == "aant_inw_priority" %}
         <td>{% render_field form.aant_inw_priority class+="form-control" %}</td>
         {% endif %}
  </tr>
{% endwith %}

or just create a custom templatetag.

Upvotes: 1

Related Questions