django-formsjinja2django-widget-tweaks

Using django-widget-tweaks with Jinja2 template engine


I'm using django v1.11.7 with Jinja2 v2.10 as the template engine.

In my website, I wish to render forms using bootstrap. I found out that django-widget-tweaks can be used for this integration.

This package won't work with Jinja templates, since it needs to load a custom tag set into the Jinja environment. Loading tag sets can be complex, since I may need to write an extension.

Is there an easy way to get django-widget-tweaks to work with Jinja? Or is there another way for integrating boostrap with Jinja?


Solution

  • A little late but maybe this can help.

    What I did is import the function I wanted to use and called them in my jinja templates:

    app_root.jinja2.py

    from jinja2 import Environment
    from jinja2 import contextfunction
    
    from widget_tweaks.templatetags.widget_tweaks import render_field
    
    
    def environment(**options):
        env = Environment(**options)
        env.globals.update({
            'render_field': render_field,
        })
        return env
    

    In template

    {% set class = class + "my-html-class" %}
    {{ render_field(field, class) }}
    

    EDIT: Anyone with a little bit of Jinja and template tag experience knows this won't work. For my current needs, I defined the two following function in my jinja config and will evaluate my needs at a later time.

    def set_attr(bound_field, attr, value):
        bound_field.field.widget.attrs[attr] = value
        return bound_field
    
    def add_class(bound_field, value):
        try:
            bound_field.field.widget.attrs['class'] += value
        except KeyError:
            bound_field.field.widget.attrs['class'] = value
        return bound_field
    

    EDIT 2 Other useful link: https://github.com/niwinz/django-jinja/issues/140

    To make this solution work, I had to make these changes: jinja2.py

    from jinja2 import Environment
    from widget_tweaks.templatetags.widget_tweaks import add_class
    from widget_tweaks.templatetags.widget_tweaks import set_attr
    
    
    def environment(**options):
        env = Environment(**options)
        env.filters['set_attr'] = set_attr
        env.filters['add_class'] = add_class
        return env
    

    template.html

    {{ form.field |set_attr('attr:val') }}
    {{ form.field |add_class('my_class') }}