How to change Submit button text from a view in crispy-forms?

django, django-crispy-forms, python

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

Problem

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?

Original source