3

我为此模型使用了 Django表单集:

class Book(models.Model):
    book_id=models.AutoField(primary_key=True,unique=True)
    book_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    author=models.ForeignKey(Author)

表单集是这样定义的:

BookFormset = inlineformset_factory(Author, Book, 
    fields=('book_id','book_name', 'publisher_name'), extra=1, 
    can_delete=False)

模板是:

{{ 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 }}
    {% 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>

这些字段按列显示,但我希望它们按行显示。

上面的代码产生如下输出:

Book name   Publisher name

book_field       Publisher_field

我希望输出看起来像这样:

Book name   book_field

Publisher name   Publisher_field

我怎样才能做到这一点?

4

2 回答 2

2

在您的模板中,您有两个<tr>元素,每个元素都包含一个循环form.visible_fields,每次迭代都会生成一个<th>or <td>

更改这一轮,以便您有一个循环form.visible_fields,其每次迭代都包含一个包含 a和 a 的<tr>元素。像这样:<th><td>

<table id="formset" class="form">
{% for form in formset.forms %}
  {% for field in form.visible_fields %}
  <tr class="{% cycle row1,row2 %}">
    <th>{{ field.label|capfirst }}</th>
    <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>
  </tr>
  {% endfor %}
{% endfor %}    
</table>
于 2013-04-06T09:43:26.790 回答
2

上面的示例似乎显示了按列布局,这似乎是表单集呈现自身时的默认布局。

要使其按行排列,请使用以下内容:

<table>
    {% for form in formset.forms %}
        {% if forloop.first %}
            <thead>
                {% for field in form.visible_fields %}
                    <th>{{ field.label }}</th>
                {% endfor %}    
            </thead>
            <tbody>
        {% endif %}

        <tr class="{% cycle row1,row2 %}">                        
            {% for field in form.visible_fields %}
                <td>
                    {% if forloop.first %}
                        {% for hidden in form.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                    {% endif %}

                    {{ field.errors.as_ul }}
                    {{ field }}
                </td>
            {% endfor %}
        </tr>
        {% if forloop.last %}
            </tbody>
        {% endif %}
    {% endfor %}    
</table>
于 2014-08-21T12:34:57.410 回答