python - 使用 django-crispy 组合布局时出错

标签 python django layout django-crispy-forms

我想使用通用布局在 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"),
            )
        )

因此,我需要帮助才能正确处理并传递给其他表单。

最佳答案

您正在创建一个 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"),
            )
        )

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

关于python - 使用 django-crispy 组合布局时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30576324/

相关文章:

python - pandas - 掩码适用于整个数据框但适用于选定的列?

python - Django 下一页在登录页面中不起作用

Django(CSRF token 丢失或不正确)抑制日志记录

Django 管理员无法使用自定义用户模型正确登录

java - 将空布局与卡片布局相结合 [java]

python - sympy+matplotlib 不绘制几何图元

Python 和 OpenCL 问题

html - 开放图协议(protocol) : Reasons to include more than one image anyone?

ios - ViewController 异常改变大小

python - 当使用 pandas 连续出现多个组时,如何按组添加数字