【问题标题】:Django Crispy Forms CustomLayout with Fieldset带有 Fieldset 的 Django Crispy Forms CustomLayout
【发布时间】:2020-04-06 22:59:58
【问题描述】:

所以我想构建一个自定义布局,为我拥有的表单扩展 LayoutObject

class NewBookForm(LayoutObject):


    template = 'library/layouts/new_book_layout.html'

    def __init__(self, fields, template=None, *args, **kwargs):
        self.fields = fields
        # Overrides class variable with an instance level variable
        if template:
            self.template = template

    def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
        fields = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs)

        template = self.get_template_name(template_pack)
        return render_to_string(template, {'fields': fields})

我用

来称呼它
    self.helper.layout = Layout(
            NewBookForm(Fieldset('book_id', 'name', 'author'))
    )

现在 Django 说“模板不存在”。 但是,这并没有让我得到我正在寻找的结果。

更新 1:

现在 library/layouts/new_book_layout.html 有类似的东西

<div class="w-40 mr-2">
  {{name|as_crispy_field}}
  {{name.errors.as_ul }}
  {{author|as_crispy_field}}
  {{author.errors.as_ul }}
</div>

我现在收到错误:

CrispyError at library/layouts/new_book_layout.html

|as_crispy_field got passed an invalid or inexistent field

并突出显示:

{{name|as_crispy_field}}

【问题讨论】:

  • 能否包含堆栈跟踪。
  • 对问题进行了编辑以添加您的问题

标签: django django-crispy-forms


【解决方案1】:

这是因为一旦你调用 get_rendered_fields 它返回一个字符串对象而不是脆对象,所以你应该使用 |as_crispy_field 过滤器而不是使用 |safe 过滤器,因为你的上下文包含的是一个 HTML 字符串。

【讨论】:

    猜你喜欢
    • 2016-12-20
    • 2021-01-08
    • 2022-01-04
    • 2019-07-31
    • 1970-01-01
    • 2019-12-31
    • 2012-06-16
    • 2015-02-02
    • 2014-06-22
    相关资源
    最近更新 更多