Reputation: 47
in views.py
def index(request):
all_user = Manvi_User.objects.all()
ordering = all_user.order_by('dob')
return render(request, 'index.html', {'ordering': ordering})
in My tag.py
@register.assignment_tag
def year():
return "2017"
In my index.html
{% year as years %}
{% for Manvi_User in ordering %}
<li>{{ Manvi_User.first_name }}</li>
{{years}}
{{ Manvi_User.dob}}
{% if forloop.counter|divisibleby:3 %}
{{ years = years+1}}
{% endif %}
{% endfor %}
I get problem at
years = years +1
I want to display starting first 3 name with year 2017 then 3 name with year 2018 and next 3 name should be with year 2019
Upvotes: 1
Views: 732
Reputation: 1204
Pass the forloop counter value to a custom template filter tag, perform your calculations there and then return it. Although, it's best to keep logical code restricted to the view - you should see if there is any way to move this piece of code to your view
my_tag.py,
from django import template
register = template.Library()
@register.filter
def calculate_year(year, loop_counter):
try:
year = int(year)
except ValueError:
return None
else:
return str(year + (loop_counter//3)) # This will work on python 2.x and 3.x
#return str(year + (loop_counter/3)) # This will not work on python 3.x
in your template,
{% load my_tag %}
<!-- Some code inside your forloop -->
{{year|calculate_year:forloop.counter}}
Upvotes: 1