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?
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.
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.
Django Crispy Forms is a Python package that styles the Django forms with the help of built-in template packs.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With