pythonhtmldjangoformset

get name attr value for formset with appropriate prefix and formset form index


I am manually displaying modelformset_factory values in a Django template using the snippet below. One of the inputs is using the select type and I'm populating the options using another context value passed from the view after making external API calls, so there is no model relationship between the data and the form I'm trying to display.

view

my_form = modelformset_factory(MyModel, MyModelForm, fields=("col1", "col2"), extra=0, min_num=1, can_delete=True,)

template

{{ my_form.management_form }}
{% for form in my_form %}
    <label for="{{ form.col1.id_for_label }}">{{ form.col1.label }}</label>
    {{ form.col1 }}
    
    <label for="{{ form.col2.id_for_label }}">{{ form.col2.label }}</label>
        <select id="{{ form.col2.id_for_label }}" name="{{ form.col2.name }}">
              <option disabled selected value> ---- </option>
              {% for ctx in other_ctx %}
                  <option value="{{ ctx.1 }}">{{ ctx.2 }}</option>
              {% endfor %}
        </select>
{% endfor %}

The other_ctx populating the select option is a List[Tuple]

I am trying to get the name value for the col2 input using {{ form.col2.name }} but only col2 is getting returned instead of form-0-col2. I could prepend the form-0- value to the {{ form.col2.name }} but wondering if:

  1. I could do the above automatically? I'm assuming the formset should be aware of the initial formset names with appropriate formset index coming from the view.
  2. Is there a way to include the select options in the initial formset that is sent to the template so that I can simply use {{ form.col2 }}?

Just saw that I could use form-{{ forloop.counter0 }}-{{ form.col2.name }} as an alternative as well, if getting it automatically does not work.


Solution

  • I think what you are after is form.col2.html_name - docs

    This is the name that will be used in the widget’s HTML name attribute. It takes the form prefix into account.