使用Djangoscrispy组合布局时出错

2024-09-30 14:32:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Django crispy用一个公共布局在Django中构建几个表单。我阅读了关于组合布局的简明文档,但我无法自己完成,因为我收到了错误消息:

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"),
            )
        )

所以,我需要帮助把这件事做好,然后转到其他表格。在


Tags: thedjangoselfformhelperinitwithargs
1条回答
网友
1楼 · 发布于 2024-09-30 14:32:58

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

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

#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"),
            )
        )

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

相关问题 更多 >