所以我想构建一个自定义布局,为我拥有的表单扩展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}}
这是因为一旦你调用get_rendered_fields
它就会返回一个字符串对象而不是一个脆皮对象,所以你应该使用|safe
过滤器,而不是使用|as_crispy_field
过滤器,因为你的上下文包含一个 HTML 字符串。