Skip to main content
 首页 » 编程设计

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

2025年05月04日7think

我想使用通用布局在 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() 对象,这是问题的根源。