Skip to content

Instantly share code, notes, and snippets.

@jmorakuebler
Last active November 13, 2019 12:09
Show Gist options
  • Save jmorakuebler/518cb0f375e02eebdfa284d553ab3ea3 to your computer and use it in GitHub Desktop.
Save jmorakuebler/518cb0f375e02eebdfa284d553ab3ea3 to your computer and use it in GitHub Desktop.
Custom ModelForm class with django-crispy-forms' FormHelper. You can optionally provide your own layout
from django.forms import ModelForm
from crispy_forms.helper import FormHelper
from crispy_forms.bootstrap import FormActions
from crispy_forms.layout import Layout, HTML, Div, Submit
# Put it variable to avoid writing it twice
buttons_layout = Layout(
Div(
HTML('<br>'),
FormActions(
Submit('submit', 'Save'),
HTML('<a class="btn btn-secondary" href="{{ request.META.HTTP_REFERER }}">Cancel</a>')
),
css_class='row justify-content-center',
),
)
class CrispyModelFormWithHelper(ModelForm):
"""
Custom ModelForm with a FormHelper.
Optionally a helper_custom_layout can be provided.
"""
helper_custom_layout = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
custom_layout = self.helper_custom_layout
self.helper = FormHelper(self)
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-md-12'
self.helper.field_class = 'col-md-12'
if custom_layout:
self.helper.layout = Layout(custom_layout, buttons_layout)
else:
self.helper.layout.append(buttons_layout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment