django-widget-tweaks icon indicating copy to clipboard operation
django-widget-tweaks copied to clipboard

how to pass dynamic value in render_field method

Open prasofty opened this issue 9 years ago • 8 comments

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 %}

prasofty avatar Jul 29 '15 12:07 prasofty

+1

sethlivingston avatar Oct 05 '15 15:10 sethlivingston

+1

SteinRobert avatar Oct 07 '15 07:10 SteinRobert

+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.

ajeebkp23 avatar Nov 12 '15 07:11 ajeebkp23

+1

jordaneremieff avatar May 11 '16 13:05 jordaneremieff

+1

ram0973 avatar Sep 22 '16 13:09 ram0973

+1

Mohre avatar Jan 07 '17 14:01 Mohre

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 %}

gitanupam avatar May 30 '17 09:05 gitanupam

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 %}

jorgeav527 avatar Mar 23 '22 15:03 jorgeav527