Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 643
Adam Silver Avatar asked Feb 10 '14 05:02

Adam Silver


People also ask

How do I change the submit button text?

The value attribute can be used to change the text of the form submit button. Use value attribute within <input> of type="submit" to rename the button.

What are crispy form tags?

crispy template tag - a one line form Template tags are processed by Django's template engine in order to perform various tasks, in this case - to output the form's HTML based on the code behind it.

What is crispy form Django?

Django Crispy Forms is a Python package that styles the Django forms with the help of built-in template packs.


2 Answers

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
like image 67
kviktor Avatar answered Oct 26 '22 22:10

kviktor


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
like image 22
Munim Munna Avatar answered Oct 26 '22 23:10

Munim Munna