【问题标题】:Error composing layouts with django-crispy使用 django-crispy 组合布局时出错
【发布时间】:2015-08-15 01:54:20
【问题描述】:

我想在 Django 中使用 django-crispy 使用通用布局构建多个表单。我阅读了有关编写布局的清晰文档,但我无法自己完成,因为我收到消息错误:

append() 只接受一个参数(给定 2 个)。

请参阅下面的代码:

# a class with my common element
class CommonLayout(forms.Form, Layout):
    code = forms.CharField(
        label='Serial Number',
        max_length=12,
        required=True,
    )

    def __init__(self, *args, **kwargs):
        super(CommonLayout, self).__init__(*args, **kwargs)

        self.helper = FormHelper(self)
        self.helper.form_method = 'POST'

        self.helper.layout = Layout (
            Field('code', css_class='form-control', placeholder='Read the Serial Number'),
        )

#the class with the form
class CollectionForms(forms.Form):

    def __init__(self, *args, **kwargs):
        super(CollectionForms, self).__init__(*args, **kwargs)

        self.helper = FormHelper(self)
        self.helper.form_action = 'collection'

        self.helper.layout.append(
            CommonLayout(),
            FormActions(
                StrictButton('Pass', type="submit", name="result", value="True", css_class="btn btn-success"),
            )
        )

所以,我需要帮助来解决这个问题并将其传递给其他表单。

【问题讨论】:

  • 问题出在:self.helper.layout.append(CommonLayout(), FormActions( StrictButton('Pass', type="submit", name="result", value="True", css_class="btn btn-success"), ) )
  • @Igor 当我将 self.helper.layout.append() 更改为 self.helper.layout= Layout() 时,布局是在没有我在 CommonLayout 中输入的情况下构建的。我在终端中有消息:WARNING:root:Could not resolve form field

标签: python django layout django-crispy-forms


【解决方案1】:

您正在创建一个CommonLayout 表单类,并尝试让其他表单继承该表单的布局。

实现此目的的一种方法是使CollectionForms 继承自CommonLayout,如下所示:

#the class with the form
class CollectionForms(CommonLayout):

    def __init__(self, *args, **kwargs):
        super(CollectionForms, self).__init__(*args, **kwargs)

        self.helper.form_action = 'collection'

        self.helper.layout.append(
            FormActions(
                StrictButton('Pass', type="submit", name="result", value="True", css_class="btn btn-success"),
            )
        )

注意 this 继承了 CommonLayout 形式的 Layout() 对象,并扩展了它。您不是在 CollectionForms 类中重新初始化 FormHelper 对象,而是在修改从 CommonLayout 表单类创建的 FormHelper 对象。您之前的示例没有从CommonLayout 继承FormHelper,它创建了一个新的Layout() 对象,这是您问题的根源。

【讨论】:

    猜你喜欢
    • 2012-06-16
    • 1970-01-01
    • 2013-07-21
    • 2014-02-03
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多