Django:在表单字段之间显示文本

发布于 2024-12-02 14:11:35 字数 572 浏览 0 评论 0原文

大家好,Stackoverflow,

我正在通过循环显示一个大表单:

    <table>
    {% for field in projectDetailForm %}
    <tr>
        <td> {{ field.label_tag }} </td>
        <td> {{ field }} </td>
    </tr>
    {% endfor %}
    </table>  

我想在几个表单字段之后用表单字段中断表格以显示更多说明。由于表单相当大(20个字段),我想避免每个表单字段的“手动显示”(如所述此处)。

有没有办法在循环内显示文本表单,无论是在第 x 个循环之后还是在特定表单字段之后?

感谢您的建议!

Hi Stackoverflow people,

I am displaying a large form through a loop:

    <table>
    {% for field in projectDetailForm %}
    <tr>
        <td> {{ field.label_tag }} </td>
        <td> {{ field }} </td>
    </tr>
    {% endfor %}
    </table>  

I would like to interrupt the table with the form fields after a few form fields to display more explanations. Since the form is fairly large (20 fields), I would like to avoid the "manual display" of each form field (as described here).

Is there a way to display the text form within the loop, either after the x-th loop or after a specific form field?

Thank you for your advice!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧梦荧光笔 2024-12-09 14:11:35

我会使用 forloop.counter 或在表单初始化时在表单字段上设置自定义属性,并以与显示 field.label_tag 相同的方式显示该属性

I would either use forloop.counter or set a custom attribute on a form field on form initialization and display the attribute the same way you display field.label_tag

羁绊已千年 2024-12-09 14:11:35

您可以向表单添加一个方法,该方法将按部分返回字段。像这样:

def by_5(self):
    iterable = iter(self)
    zipped = zip(*([iterable] * 5)) # replace 5 by desired n
    for z in zipped:
        yield z
    remained = list(iterable)
    if remained:
        yield remained

然后在模板中:

<table>
{% for fields in projectDetailForm.by_5 %}
    {% for field in fields %}
    <tr>
        <td> {{ field.label_tag }} </td>
        <td> {{ field }} </td>
    </tr> 
    {% endfor %}
    <tr><td colspan="2">Hi there!</td></tr>
{% endfor %}
</table>  

You can add a method to your form, which will return fields by portions. Something like:

def by_5(self):
    iterable = iter(self)
    zipped = zip(*([iterable] * 5)) # replace 5 by desired n
    for z in zipped:
        yield z
    remained = list(iterable)
    if remained:
        yield remained

Then in template:

<table>
{% for fields in projectDetailForm.by_5 %}
    {% for field in fields %}
    <tr>
        <td> {{ field.label_tag }} </td>
        <td> {{ field }} </td>
    </tr> 
    {% endfor %}
    <tr><td colspan="2">Hi there!</td></tr>
{% endfor %}
</table>  
画骨成沙 2024-12-09 14:11:35

您可以使用 {{ forloop.counter }}{{ forloop.counter0 }} (分别为 1 索引和 0 索引)。

有关更多信息,请查看此 Djangobook 链接。

There is a {{ forloop.counter }} and {{ forloop.counter0 }} (1-indexed and 0-indexed respectively) that you can use.

For a few more information, check this Djangobook link.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文