I used palestamp's response as a guide to build a more generic CustomCrispyField
. You can pass extra_context
as a kwarg
to CustomCrispyField
. extra_context
is just a dictionary that I access in my custom template that I copied from crispy_forms
.
from crispy_forms.layout import Field
from crispy_forms.utils import TEMPLATE_PACK
class CustomCrispyField(Field):
extra_context = {}
def __init__(self, *args, **kwargs):
self.extra_context = kwargs.pop('extra_context', self.extra_context)
super(CustomCrispyField, self).__init__(*args, **kwargs)
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs):
if self.extra_context:
extra_context = extra_context.update(self.extra_context) if extra_context else self.extra_context
return super(CustomCrispyField, self).render(form, form_style, context, template_pack, extra_context, **kwargs)
And I would use it like so in my form:
self.helper.layout=Div(CustomCrispyField('my_model_field', css_class="col-xs-3", template='general/custom.html', extra_context={'css_class_extra': 'value1', 'caption': 'value2'})
And my template would have code similar to the following:
{% crispy_field field %}
<button class="btn {{ css_class_extra }}">{{ caption }}</button>