djangodjango-bootstrap4

Generate kwargs for Django bootstrap_field


I'm trying to auto generate a list of fields for a Django form with the bootstrap4 package.

I'm defining the kwargs in a dict, and want to loop through the fields and apply any kwargs to the bootstrap_field tag that comes with bootstrap4.

Data

data = [
    {
        "name": "school_1",
        "args": {
            "show_label": True,
        },
    },
    {
        "name": "school_2",
        "args": {
            "show_label": False,
        },
    },
]

Template:

{% for field in form %}
    {% bootstrap_field field field|get_kwargs:data %}
{% endfor %}

Template filter:

from django.template.defaulttags import register
@register.filter
def get_kwargs(formfield, data):
    item = next((item for item in data if item["name"] == formfield.name), None)
    if item:
        return item.get('args'):
    return None

The issue is the bootstrap_field tag is using what the filter returns as an arg, not a kwarg. Is there anything I can do or do I need to replace bootstrap_field?

Error render_field() takes 1 positional argument but 2 were given

args    (<django.forms.boundfield.BoundField object at 0x10f834240>,
 {'show_label': True})
kwargs  {}

Solution

  • I think kwargs unpacking is not available in django templating language. What you can do is make your filter render actual field for you like this

    from django.template.defaulttags import register
    from bootstrap4.templatetags.bootstrap4 import bootstrap_field
    
    
    @register.filter
    def get_kwargs(formfield, data):
        item = next((item for item in data if item["name"] == formfield.name), None)
        kwargs = item.get('args') or {}
        return bootstrap_field(formfield, **kwargs)
    

    and in template just do

    {{ field|get_kwargs:data }}
    

    Ps: you can change name of get_kwargs to something more meaningful if you implement it this way (like render_field)