Milano Slesarik Milano Slesarik - 1 year ago 98
Python Question

Django - string from variable inside template tag

I can't figure out how to send multiple arguments into custom template filter.

The problem is that I use template variables as an arguments.


def is_scheduled(product_id,dayhour):
day,hour = dayhour.split(',')
return Product.objects.get(id=product_id).is_scheduled(day,hour)


{% if|is_scheduled:"7,22" %}...{% endif %}

The line above would work correctly like I put two arguments - 7 and 22 into the filter (tested - works). The problem is that I want to put variables instead of plain text/string as an argument.

In my template:

{% with day=forloop.counter|add:"-2" hour=forloop.parentloop.counter|add:"-2" %}

Now, I want to use
{{ day }}
{{ hour }}
as an arguments.

I tried for example:

{% if|is_scheduled:"{{ day }},{{ hour }}" %}...{% endif %}

But this raises:

Exception Value: invalid literal for int() with base 10: '{{ day }}'

Do you have any ideas?

Answer Source

You don't need the {{}} when you're inside the {% %}. Just use the names directly in that tag and use the string concat template syntax add.

In case day and hour are strings, a type conversion to string will be required before concating the strings:

{% with day|stringformat:"s" as sday hour|stringformat:"s" as shour %}
    {% with sday|add:","|add:shour as arg %}
        {% if|is_scheduled:arg %}...{% endif %}
    {% endwith %}
{% endwith %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download