[Django]-Horizontal (per-row) forms in a Django formset

39👍

You might want to try something like this http://www.djangosnippets.org/snippets/1442/

{{ formset.non_form_errors.as_ul }}
<table id="formset" class="form">
{% for form in formset.forms %}
  {% if forloop.first %}
  <thead><tr>
    {% for field in form.visible_fields %}
    <th>{{ field.label|capfirst }}</th>
    {% endfor %}
  </tr></thead>
  {% endif %}
  <tr class="{% cycle row1 row2 %}">
  {% for field in form.visible_fields %}
    <td>
    {# Include the hidden fields in the form #}
    {% if forloop.first %}
      {% for hidden in form.hidden_fields %}
      {{ hidden }}
      {% endfor %}
    {% endif %}
      {{ field.errors.as_ul }}
      {{ field }}
    </td>
  {% endfor %}
  </tr>
{% endfor %}
</table>
👤Dave

8👍

I suggest using form.as_ul and styling it with your CSS to make it all on one row. You can do that with ul li { display: inline; } or of course, substitute a class or ID if you don’t want to affect all ULs in that manner.

Here’s the relevant section of the Django docs: http://docs.djangoproject.com/en/dev/topics/forms/#displaying-a-form-using-a-template

Edit:
To address your need for a table, you’d like want to do something like this… edited some more.

It’s difficult to put all of these forms in a table, and still have valid HTML. A form element can surround a table, or be inside a <td>… though this will likely still work.

<thead>
  <tr>
   {% for field in form %}
     <th>{{ field.label }}</th>
   {% endfor %}
  </tr>
</thead>

<tbody>
 <tr class="table_row">
  <form action="/something/" method="post">
    {% for field in form %}
      <td>
       <table>
        <tr><td>{{ field.label }}</td></tr>
        <tr><td>{{ field }}</td></tr>
       </table>
      </td>
    {% endfor %}
   </form>
  </tr>
 </tbody>
👤JAL

0👍

Here is very basic form to display all fields in line along with tags as headers.

<table class="table">
    <tr>    
        {% for field in form %}
            <th>{{ field.label }}</th>
        {% endfor %}
    </tr>
    <form method="POST"> {% csrf_token %}
        {% for field in form %}
                <td>{{ field }}</td>
            {% endfor %}
    </form>
</table>

Leave a comment