Skip to content Skip to sidebar Skip to footer

Python-django: Ifchanged Template Tag

Here i am getting employee with duration from database.Same employee with 2 or 3 records. so gettting employee duration and adding and displaying,if employee ID changed then again

Solution 1:

I believe there are a couple of issues to deal with here. First of all I see you want to print an item of the 'result' variable, depending on the position of the forloop counter. This is not directly possible in django templates (for various fair reasons). To quickly solve this without reorganizing your data in the view, you can define a custom filter that simply returns a list item on the specified index. You could put this in your templatetags/myfilters.py:

from django importtemplateregister = template.Library()

@register.filter
def getitem(mylist, index):
    return mylist[index]

Then, to reset the forloop counter when 'laEmpNum' changes you should use the 'regroup' django template tag like this:

{% load myfilters %}
{% regroup DBShots1 by laEmpNum as eachScList %}
{% for eachScGrp in eachScList %}
    {% for eachSc in eachScGrp.list %}
    <tr><tdbgcolor="#FFFACD"width="1%">{{ forloop.counter }} </td><tdbgcolor="#CCFACD"width="1%">{{ eachSc.sName }}</td><tdbgcolor="#CCF0F5"width="1%">{{ eachSc.duration }}</td><tdbgcolor="#CCFACD"width="1%">{{ eachSc.frames }}</td><tdbgcolor="#CCFACD"width="5%">{{ GetEmpDept }} - {{ getEmpName.emp_name }} - {{ eachSc.laEmpNum }}</td></tr>
    {% endfor %}
    <tr><td></td><td></td><tdbgcolor="#FFFACD"width="1%">Tot={{ result|getitem:forloop.counter0 }}</td></tr>
{% endfor %}

The first line loads our custom filter library. The last part uses the custom filter to retrieve a result item based on the iteration over the 'laEmpNum' groupper.

Post a Comment for "Python-django: Ifchanged Template Tag"