Malik Aqib
Malik Aqib

Reputation: 513

render fields in form as pairs

 <form action="/contact/" method="post">
 {% for field in form %}
 <div class="fieldWrapper">
    {{ field.errors }}
    {{ field.label_tag }}: {{ field }}
 </div>
{% endfor %}
<p><input type="submit" value="Send message" /></p>
</form>

the code works perfectly with a data entry per line, but in order to save space, i want to render the data in 2 sets per line..(i.e 2 fields per line and the use <br>)

it should look like

field1.tag : field1,   field2.tag: field2.

or some similar solution

Upvotes: 2

Views: 59

Answers (1)

Tadeck
Tadeck

Reputation: 137390

Best solution: styling

The best solution is to solve it on styling level.

Like that (see demo):

  • template:

    <form action="/contact/" method="post">
        {% for field in form %}
            <div class="fieldWrapper">
                {{ field.errors }}
                {{ field.label_tag }}: {{ field }}
            </div>
        {% endfor %}
        <p><input type="submit" value="Send message" /></p>
    </form>
    
  • CSS:

    .fieldWrapper {
        float: left;
        width: 50%;
    }​
    

Alternative solution: document structure

Alternatively you can use more complex template code to generate rows and columns. To do that, you can use Django's for loop variables, like:

  • forloop.counter (or forloop.counter0) - containing number of the current element in the loop,
  • forloop.first - True if current element is the first, False otherwise,
  • forloop.last - True if current element is the last, False otherwise,

but presentation issues ("saving space on the screen") should be solved on styling layer.

Upvotes: 1

Related Questions