Question

In my forms.py I have the following:

self.helper.layout = Layout(
    Fieldset(
        None,
        'name'
    ),
    FormActions(
        Submit('submit', 'Add Thing', css_class='btn-primary')
    )
)

But I am using the same view to add and edit the item. So I want to change the button text (Add Thing above) based on some condition in my views.py. How can I do that?

Was it helpful?

Solution

One way would be to pass an argument to the form class that determines the Submit button text.

A dummy example:

view

...
form = MyFormClass(is_add=True)
...

form class

class MyFormClass(forms.Form):
    def __init__(self, *args, **kwargs):
        self.is_add = kwargs.pop("is_add", False)
        super(MyFormClass, self).__init__(*args, **kwargs)

    @property
    def helper(self):
        helper = FormHelper()
        helper.layout = Layout(
            FormActions(
                Submit('submit', 'Add Thing' if self.is_add else 'Edit thing', css_class='btn-primary')
            )
        )
        return helper

OTHER TIPS

This is a simple improvement over @kviktor's answer. Prepare your form to accept an additional argument submit_label and use it to name your button.

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        submit_label = kwargs.pop("submit_label", "Submit")
        super().__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.layout = Layout(
            Fieldset(
                None,
                'name'
            ),
            FormActions(
                Submit('submit', submit_label, css_class='btn-primary')
            )
        )

Override the get_form method of your view to instantiate the form yourself passing the value of submit_label depending on your conditions.

class MyView(generic.FormView):
    def get_form(self):
        form = MyForm(**super().get_form_kwargs(), submit_label="Add Thing")
        return form
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top