如何在HTML页面中访问wagtail FreeForm的每个字段?

时间:2018-01-08 08:13:14

标签: python django wagtail wagtail-streamfield

我通过扩展下面的WagtailFormBlock创建了wagtail FreeForm。我可以使用wagtail admin interface创建不同的表单。

文件名:blocks.py

from wagtailformblocks.blocks import WagtailFormBlock

class MyForm(WagtailFormBlock):

    class Meta:
        app_label = 'demo'

这是models.py文件,我在其中创建了页面并为此页面分配了表单。

文件名:models.py

from wagtail.wagtailcore.models import Page
from wagtailformblocks.models import BaseForm
from wagtail.wagtailcore.fields import StreamField


class FormType(BaseForm):

    class Meta:
        verbose_name = "Form Type"

class ImagePage(Page):
    template = 'wagtail_demo/image_page.html'

    content = StreamField([
        ('my_forms', MyForm()),
    ])

    content_panels = Page.content_panels + [
        StreamFieldPanel('content'),
    ]

这是我想要呈现表单字段的image_page.html页面。

文件名:image_page.html

{% load wagtailcore_tags %}
{% with blocks=self.content %}
    {% for block in blocks %}
        {{ block }}
    {% endfor %}
{% endwith %}

它显示与此页面关联的表单的所有字段。我想单独访问相关表单的每个字段(e.g.: field name etc.),因为有时我需要使用javascript在提交按钮之前添加字段。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

要更好地控制表单块的呈现方式,您可以轻松覆盖块上template内的Meta属性。

首先,使用meta中的模板属性调整自定义WagtailFormBlock类。我从CustomFormBlock将该类重命名为MyForm,因为这样可以更容易理解此类是流域块,而不是表单。

# file: blocks.py
class CustomFormBlock(WagtailFormBlock):

    class Meta:
        # template variable has been overridden...
        template = 'demo_app/wagtailformblocks/form_block.html'
        app_label = 'demo'

然后,在/templates/demo_app/wagtailformblocks/form_block.html中创建模板。您可以从WagtailFormBlocks codebase

复制并粘贴此块的默认模板开始
{% load static %}

<script src="{% static 'wagtailformblocks/js/formhandler.js' %}"></script>

<form action="{{ action_url }}" id="wagtailformblock_{{ form_id }}">
    {% csrf_token %}
    {% for field in form %}
        <div class="fieldWrapper">
            <strong>Custom Per Field Content for `{{ field.name }}`</strong>
            {{ field.errors }}
            {{ field.label_tag }} {{ field }}
            {% if field.help_text %}
            <p class="help">{{ field.help_text|safe }}</p>
            {% endif %}
        </div>
    {% endfor %}
    <input type="submit">
</form>

这就是您需要做的全部,现在每当您使用CustomFormBlock将表单链接到流场内容时,它都会使用您提供的模板自动呈现。

您可以在Django文档中看到有关如何以自定义方式呈现表单的更多文档:working with form templates

注释