String to Int --> Django - django

[{'age': 1}] being returned something alike to this after a query. This is in my view. Now in my HTML I want to refer to that value returned - in this case '1' if {{}} > 1 ... do something but it cannot do this because Could not parse the remainder: '{{age}}' from '{{age}}'. However if I define a random integer value in my view set it as i.e. 10 I can very easily refer to this variable in my html no problem. I'm presuming it's because it's printing'age' rather than just returning the result from the database. Any solutions to this ? I'm thinking about creating a definition which returns it into a string

You want {% if number > 2 %}. You use {{ number }} to include a variable in the template, but you don't use the double braces inside a template tag.

Related

How to list only item containing string X in a string Y from a dictionnary in Jinja2

I’m trying to obtain the count of all title containing a specific string from a dictionary in a jinja template.
I have tried many variant with select and other test and haven’t found the right way to do so.
This is not for ansible for which I have found many solutions to fix this issue.
Also the test equalto does not work since I do not have an exact match on the string and doesn’t seem to take regex.
{{ Dictionnary | selectattr("title", "in","MyString") | list | count }}
It seems that the string never gets properly evaluated because it always returns 0.
The selectattr without test return the right number of total titles.
I wonder if we could evaluate it with an if statement somehow.

Is there a Django template tag that will convert a percentage to a human readable format?

For example:
Convert 0.01 to 1%
Convert 0.001 to 0.1%
Convert 0.5 to 50%
I see in humanize there is nothing and I could not find anything in the Django documentation. I have tried {{ value|multiply:100 }}% without success. I know I can write my own template tag but I prefer to avoid doing that whenever possible.
UPDATE: I have also looked into the widthratio tag. For a value of 0.001 it goes to 0%. This is not what I want, unfortunately.
I went ahead and created a template tag filter like this:
#register.filter
def to_percent(obj, sigdigits):
if obj:
return "{0:.{sigdigits}%}".format(obj, sigdigits=sigdigits)
else: return obj
I was surprised to see the link shared in another answer didn't have a clean solution like that yet. The best one I saw used a try block instead of the if obj... I personally want to see an error in my use case, but that's up to you.
Still, good to know there isn't a more "Django" way to do it that I saw. You'd use this in your template like...
{{{{mymodel.some_percentage_field|to_percent:2}}
where 2 is the number of significant digits you want.
As Michael mentioned above, I will suggest you to write your own template tag for that : https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/
You can do this with Django built-in template tag withraatio
{% widthratio this_value max_value max_width as width %}
If this_value is 175, max_value is 200, and max_width is 100, the image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88).
You can also see the details here
Maybe use one of these solutions: Is there a django template filter to display percentages?
Hope it helps. If not, write your own simple filter :)
If you only have to format a number with percent, for example "65%" :
{{ number|stringformat:"d%%" }}

Loop through an array django - slightly more complex

I am using a JQuery chart library where you pass values a format like [0,2,5,9].
I have an array in my views where I currently access each index to return the value rest 1 = arr[0], rest 2 = arr[1] ... and then passing these values from the view into my HTML page and inserting the values for the chart like [res1,res2]. This is not feasible because I never know the size of the array so it'd be a constant manual approach of accessing the array. Is there a way I easily loop through each one?
Slight problem. Currently after accessing each index I convert value to an int. So I don't think I'd be able to do it via looping through the html page - it'd have to be done via views. Unless I can somehow call conversion function defined in the view in the html page?
--- views ---
array
-> returns multiple string values i.e. name = paul, name = john
-> paul = arr[0]
-> function(paul['']) converts it to a string.
--- html page ---
{{paul}}
ideally i'd like to do:
[rather than refer to each index here just loop through all array values.. but somehow calling my conversion function too on each value else what I want to do won't work. ]
{% for values in array %}
[insert each one here and call the convert int function from views]
I might misunderstood your question, but sounds like you just want to pass a list of string to the template, loop on each item in the list and do some conversion. I'm not really sure which step did you get stuck but the simplest way is to do everything in the views.py:
views.py
def view_func(request):
array = [{'Speed': 2, 'Height': 1, 'PersonID': 1}, {'Speed': 2, 'Height': 1, 'PersonID': 1}]
# do the conversion on each value in the list
converted_array = [int(i['speed']]) for i in array]
context = {'array': array, 'converted_array': converted_array}
template:
<!-- to loop on original array -->
{% for value in array %}
{{ value }}
{% endfor %}
<!-- to loop on the converted array -->
{% for value in converted_array %}
{{ value }}
{% endfor %}

why django load actually the template contents?

after runsrever my browser show this:**
> {% set enabled_scopes_class = 'scopes-' +
> '%s'|format(settings.ALL_SCOPE_ENABLED) + '-' +
> '%s'|format(settings.UNANSWERED_SCOPE_ENABLED) + '-' +
> '%s'|format((request.user.is_authenticated() and
> settings.FOLLOWED_SCOPE_ENABLED)) %} {# Some or all contents of this
> div may be dropped over the search bar via negative margins, to make
> sure that the search bar can occupy 100% of the content width. Search
> bar may have padding on the left and right to accomodate the buttons.
> `#}{# three buttons below are in the opposite order because they are
> floated at the right #}`
Please guide me the correct way to achieve my objective.
The reason you see the raw code when rendering the template, is that statements must be on a single line, both tags and comments.
For the multiline comments, you can use the comment tag:
{% comment %}
Some or all contents of this
div may be dropped over the search bar via negative margins, to make
sure that the search bar can occupy 100% of the content width. Search
bar may have padding on the left and right to accomodate the buttons.
three buttons below are in the opposite order because they are
floated at the right
{% endcomment %}
As for your set statement: I don't know about any set statement (is it a third-party tag?), but the template language is by design not nearly as powerful as Python code. The use of parentheses to group statements is not permitted, and you can't call functions with arguments in the same way you can do it in python. You also cannot concatenate values with + and format is not a defined template filter. I'd suggest you read up on templates in the documentation.
More advanced logic, like what you are trying to do here, should be done in the view function, and passed on to the context of the template.
You probably did not render your template
try something like:
from django.shortcuts import render
def myview(request):
return render(request, 'path/template.html', {})

meteor template compare/passing a variable

I want to do what should be a simple compare but I have been stuck for the longest time on this:
I have a template that calls a list template, each list is a new column.
For the first column, I do NOT want certain fields displayed. Each column has a variable {{type}}
I want to do either:
a) pass type to the list template so that list can render based on type equals something
or
b) do an compare on type before I call list (in an 'each' loop) - e.g.
{{#if $eq myVar "test"}}
Show this text
{{/if}}
Neither approach works.
This seems to be the simplest thing but I am scratching head and unable to find examples.
thank you
Max
Unsure if this does what you want to achieve, it would help if you post some of your HTML. But to do what you want in b) couldn't you do:
{{#if isEqual myVar "test"}}
...
{{/if}}
and
Template.example.helpers({
isEqual: function(var1, var2) {
return var1 === var2;
}
});
It is probably easier to use collection.find({type: someType}) to just give your template what it should show. Make someType a session variable and you are done.
This sort example shows this pattern.