django-widget-tweaks
django-widget-tweaks copied to clipboard
how to pass dynamic value in render_field method
I am using render_field inside loop how to pass loop counter value to render field methods
I tried with following code but loop counter taking as string
{% for u in formset.forms %}
{% render_field u.name class+="form-control" id="name-{{forloop.counter0}}" %}
{% endfor %}
+1
+1
+1
But, I think you should don't use
{{ }} inside {% %}
IMHO, you should have tried (of course, below code didn't worked).
{% render_field u.name class+="form-control" id="name-"+forloop.counter0 %}
Then i tried to use
with
tag like
{% with "name-"|add:forloop.counter|stringformat:"i" as foo %}
{% render_field u.name class+="form-control" id=foo %}
{% endwith %}
But above didn't work.
The problem is with with
tag in my case. I couldn't get foo
variable to as to this requirement.
{% with "name-"|add:forloop.counter|stringformat:"i" as foo %}
{{ foo }}
{% endwith %}
Above code didn't give the required out. So, with proper with
tag we should proceed.
Someone, with more experience in Django template, can help me.
IMHO,
We should create a variable with with
tag. Then pass it to render_field
like id=foo
.
I think it is the right way.
Last piece.
I would have used custom template filter to create string form me, then i will use it with with
tag.
+1
+1
+1
Thanks to @ajeebkp23's suggestion above. I had to use a dynamic css class name and and could get it work using with
{% if custom_class %}
{% with "form-control "|add:custom_class as classnames %}
{% render_field field class=classnames placeholder=field.label %}
{% endwith %}
{% else %}
{% render_field field class="form-control" placeholder=field.label %}
{% endif %}
app/templatetags/extra_tagas.py 👈🏾 create a simple tag two add two strings (StackOverflow search)
from django import template
register = template.Library()
@register.filter(name=addstr)
def addstr(arg1, arg2):
"""concatenate arg1 & arg2"""
return str(arg1) + str(arg2)
inside the form 👈🏾 {% with hxtarget="#id_order_items-"|addstr:forloop.counter0|addstr:"-price" %} so you can pass to the render_field hx-target=hxtarget
{% with hxtarget="#id_order_items-"|addstr:forloop.counter0|addstr:"-price" %}
{% render_field form.test_lab hx-target=hxtarget class="form-control" hx-swap="outerHTML" hx-get="/orders/test_lab/unit_quantity_price/" %}
{% endwith %}