07carvalho
07carvalho

Reputation: 372

Error composing layouts with django-crispy

I want to build several forms in Django with django-crispy using a common layout. I read the crispy documentation about composing layouts, but I cannot made it all by myself, because I get the message error:

append() takes exactly one argument (2 given).

See my code below:

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

So, I need help to get this right and pass to another forms.

Upvotes: 2

Views: 285

Answers (1)

YPCrumble
YPCrumble

Reputation: 28682

You're creating a CommonLayout form class and you're trying to have other forms inherit the layout of that form.

One way to achieve this is to make CollectionForms inherit from CommonLayout, like so:

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

Notice that this inherits the Layout() object from the CommonLayout form, and extends this. You aren't re-initializing a FormHelper object within your CollectionForms class, you're modifying the FormHelper object created from the CommonLayout form class. Your previous example did not inherit the FormHelper from CommonLayout, it created a new Layout() object, which is the root of your problem.

Upvotes: 1

Related Questions