how to set custom forloop start point in django template - python

There is a forloop in java where i can tell where to start and where to end:
for(int i=10;i<array.length;i++){
}
but how can i implement this int i=10 in django template? How can i set the starting and ending point on my own?
there is a forloop.first and forloop.last, but they are defined inside the loop and i cannot do something like this?:
{{forloop.first=10}}
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
{{forloop.last=20}}
I read the django doc but this feature seems to be not there

How about using built-in slice filter:
{% for athlete in athlete_list|slice:"10:20" %}
<li>{{ athlete.name }}</li>
{% endfor %}
If you need to make a numeric loop (just like python's range), you need a custom template tag, like this one: http://djangosnippets.org/snippets/1926/
See other range snippets:
http://djangosnippets.org/snippets/1357/
http://djangosnippets.org/snippets/2147/
Also see:
Numeric for loop in Django templates
By the way, this doesn't sound like a job for templates - consider passing a range from the view. And, FYI, there was a proposal to make such tag, but it was rejected because it is trying to lead to programming in the template. - think about it.

Related

How to get difference between two dates as a integer inside Django templates

I have list of two dates: ['2022-07-11', '2022-07-19'] and have to calculate difference between them as a int value: 8 inside Django templates.
I tried with:
{% with value1=date.value.1 value0=date.value.0 %}
<h3>{{ value1-value0 }}</h3>
{% endwith %}
Error:
Could not parse the remainder: '-value0' from 'value1-value0'
I also tried with timesince and timeuntilstill no result
Any way to get just get difference between as a int
That kind of calculations are better moved outside template to Custom tags.
In template:
{{ date.value.1|minus_date=date.value.0 }}
Then in custom_tags.py (or whatever you will name your file):
#register.filter(name='minus_date')
def minus_date(first_date, second_date):
# calculate in classic Python way
return result

What {% %} and {{ }} mean in HTML?

I have recently started to learn Django, so I came across with some HTML templates, but those are pretty unfamiliar for me, they mostly consist of {% and {{
For example:
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
Vote again?
What are they? Implementations from other languages or HTML syntax? I'd be happy to get some docs, websites or examples too.
The {% _________ %} are template tags. They are used to interpolate a tag into the space. Examples include extend, include, and load to name but a few. They often extend, insert, or give some sort logical functionality in some way (if conditions or loops, etc).
The {{ ___________ }} syntax is for template variables. This is used to interpolate a variable declared either as one of the built-in options or your own which you have created from any number of methods (models, view context, etc).
The Django docs are pretty thorough with use cases of all these. Another website which shortlists these to make them readily understandable is https://www.djangotemplatetagsandfilters.com/
It doesn't mean anything in html itself, it means something in Django template language. For example:
{{ choice.choice_text }}
will substitute value of that variable during template rendering.
The other one {% and %} is used for template processing, for example to indicate to template processor that some task needs to be completed. Good example is:
{% if error %}
{{ error }}
{% endif %}
That means that the variable error will be displayed (rendered) only if it exists, or to be more precise if it has some value.
The ones you are referring are jinja codes. They are very essential to work with Django and also they easy to understand when you have general understanding about python and django. You can find the documentation about jinga in this URL Jinja2 Documentation

counter in jinja2 flask

I want to make a counter
this simple code not working...
{% set count = 1 %}
{% for i in [1,2,3,4,5] %}
{% set count = count + 1 %}
{% endfor %}
<h2>found {{count}}<h2>
the result is 1
i see you can use this How to increment a variable on a for loop in jinja template? but this is not work for me
If you're using Flask and Jinja2, you can use the built in filter length.
{% set my_list = [1,2,3,4,5] %}
{% for i in my_list %}
...
{% endfor %}
<h2>found {{my_list|length}}<h2>
If that doesn't do exactly what you want, you can also expose custom filter or functions from your Flask app when it is initialized by using add_template_filter() or add_template_global()
There are situations where it's more appropriate to do the counting prior to template rendering, passing the count in to the template. You might be looking at one of those. The Jinja2 template "language" is not a full, turing-complete programming language.

python/django for loop and list attributes

So, i'm studying the Django Book, and django documentation, and I can't understand this example:
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
This is about templates and i don't how to code the Context. How can i get attribute called "name" from a list ? If i create a dictionary it will be impossible to use for loop like in this example. I have coded it like this but it's not working:
athlete_list = {'name' = ['Athlete1', 'Athlete2', 'Athlete3']}
Context({'athlete_list':athlete_list})
if i change athlete_list variable to a normal list (not a dictionary) the "athlete.name" in the template won't work too. I don't think it's a mistake in a book, and it's probably very easy to solve, but i can't get it.
I'd suspect that athlete_list is a QuerySet object containing Athlete models... (does that get mentioned anywhere?). The models will then have a .name or .age or .sport or whatever...
update - just looked at http://www.djangobook.com/en/2.0/chapter04.html - which actually doesn't appear to be the best example....
To keep the template as is, you can return a context of a list of dicts, eg:
[ {'name': 'bob'}, {'name': 'jim'}, {'name': 'joe'} ]
If you want to keep the template,you should return below.
athlete_list = ({'name':'Athlete1'},{'name':'Athlete2'},{'name':'Athlete3'})
Context({'athlete_list':athlete_list})
Your athlete_list is actually a dict
<ul>
{% for athlete_name in athlete_list.name %}
<li>{{ athlete_name }}</li>
{% endfor %}
</ul>
in templates you can access dictionary keys through . instead of through []
so in your template {{ athleate_list.name }}
would be a list of strings # ['Athlete1', 'Athlete2', 'Athlete3']

Render Externally Defined Block In Django Template

I'm writing a simple blog-like application for Django and am trying to get the effect of having a front page with posts limited to 5, with a comprehensive archive that lists something like 100 posts at a time. (100 is not realistic, just throwing a number out there)
Since the blog post blocks will look exactly the same between the two pages minus the number being shown, I'd like to put the corresponding HTML in a separate template that I can include or link to from the actual templates being rendered. I've looked over the documentation, and the include tag looked promising, but it apparently renders outside of the current context, which is not helpful to my cause, since it wouldn't get the objects to loop through. Outside of that, I can't see any other way to do what I want. Is this possible or am I just out of luck and going to have to violate DRY? Code is below to give you an idea of what I want.
Thanks
#######################
# news/frontpage.html #
#######################
{% extends "news/base.html" %}
{% block site_title %} - Front Page{% endblock %}
{% block center_col %}
{{ block.super }}
View Older Blog Posts
{% endblock %}
{% block blog_rows %}
{% for object in object_list %}
# Blog post content would go here, however it is to be included.
{% endfor %}
{% endblock %}
You're looking for an inclusion tag.
Why don't you filter for the blog posts you want to show in your view? That way you can keep the template the same:
{% for object in blogposts %}
# ...
{% endfor %}
You define blogposts in your view, which either includes 5 or 100 posts.
Ignacio is right that you want an inclusion tag, but you should know that the include tag does not render outside the current context - it very definitely uses the same context as the block it's in.
Your problem is probably that you're trying to call blogpost_set on the object_list - but the relationship is not with the list of objects, it's with each individual object in the list. You'd need to iterate through object_list and then through blogpost_set.all on each one.

Categories