Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can extra context be passed to django-crispy-forms field templates?

Inspecting the field.html template in the bootstrap3 template pack of django-crispyforms, I noticed an additional context variable, "tag", referenced. You can see this on line 12 and line 41 of the template. How can I specify a value for "tag" in the context used to render the field.html template for a particular form field?

like image 480
acspike Avatar asked Apr 22 '14 15:04

acspike


People also ask

How do you customize crispy forms?

But, previously crispy forms has templatetags to handle specific field. one of it is {{ form. field_name|as_crispy_field }} , this example below is output of it. Other options, you can handle it using specific html selectors/attributes inside your forms widget, such as html class , id , style , or else.


1 Answers

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>
like image 145
Bobort Avatar answered Oct 31 '22 16:10

Bobort