Need to convert a string to int in a django template - django

I am trying to pass in url parameters to a django template like this...
response = render_to_string('persistConTemplate.html', request.GET)
This the calling line from my views.py file. persistConTemplate.html is the name of my template and request.GET is the dictionary that contains the url parameters.
In the template I try to use one of the parameters like this...
{% for item in (numItems) %}
item {{item}}
{% endfor %}
numItems is one of the url parameters that I am sending in my request like this...
http:/someDomain/persistentConTest.html/?numItems=12
When I try the for loop above, I get an output like this....
image 1 image 2
I am expecting and would like to see the word image printed 12 times...
image 1 image 2 image 3 image 4 image 5 image 6 image 7 image 8 image 9 image 10 image 11 image 12
Can anyone please tell me what I am going wrong?

you can coerce a str to an int using the add filter
{% for item in numItems|add:"0" %}
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#add
to coerce int to str just use slugify
{{ some_int|slugify }}
EDIT: that said, I agree with the others that normally you should do this in the view - use these tricks only when the alternatives are much worse.

I like making a custom filter:
# templatetags/tag_library.py
from django import template
register = template.Library()
#register.filter()
def to_int(value):
return int(value)
Usage:
{% load tag_library %}
{{ value|to_int }}
It is for cases where this cannot be easily done in view.

Yes, the place for this is in the view.
I feel like the above example won't work -- you can't iterate over an integer.
numItems = request.GET.get('numItems')
if numItems:
numItems = range(1, int(numItems)+1)
return direct_to_template(request, "mytemplate.html", {'numItems': numItems})
{% for item in numItems %}
{{ item }}
{% endfor %}

The easiest way to do this is using inbuilt floatformat filter.
For Integer
{{ value|floatformat:"0" }}
For float value with 2 precision
{{ value|floatformat:"2" }}
It will also round to nearest value. for more details, you can check https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#floatformat.

You should add some code to your view to unpack the GET params and convert them to the values you want. Even if numItems were an integer, the syntax you're showing wouldn't give you the output you want.
Try this:
ctx = dict(request.GET)
ctx['numItems'] = int(ctx['numItems'])
response = render_to_string('persistConTemplate.html', ctx)

In my case one of the items was a string and you can not compare a string to an integer so I had to coerce the string into an integer see below
{% if questions.correct_answer|add:"0" == answers.id %}
<span>Correct</span>
{% endif %}

You can do like that: if "select" tag used.
{% if i.0|stringformat:'s' == request.GET.status %} selected {% endif %}

My solution is kind of a hack and very specific..
In the template I want to compare a percentage with 0.9, and it never reaches 1, but all the values are considered string in the template, and no way to convert string to float.
So I did this:
{% if "0.9" in value %}
...
{% else %}
...
{% endif %}
If I want to detect some value is beyond 0.8, I must do:
{% if ("0.9" in value) or ("0.8" in value) %}
...
{% else %}
...
{% endif %}
This is a hack, but suffice in my case. I hope it could help others.

Related

Was wondering why iterating through a dictionary using .keys in django would not work?

I know that .items would be useful to grab the value, but wanted to see why this would not work?
Data:
...
city_data = {
'city': json_data['name'],
'country': json_data['sys']['country'],
'temp': json_data['main']['temp'],
'feels_like': json_data['main']['feels_like'],
'temp_max': json_data['main']['temp_max'],
'temp_min': json_data['main']['temp_min']
}
return render(request, ..., context={'city_data':city_data})
template:
...
{% for key in city_data.keys %}
<li>{{city_data.key}}</li>
{% endfor %}
...
I think that the reason that it doesn't work that way is because django will look at test.key and try to look up a string "key" as an actual key to the dictionary. There are a couple ways that you could do this. One way is you could define a custom template filter that would allow you to do it. I don't know much about custom filters so I can't say how specifically to do it. Another way though is to use city_data.items in your template instead like this:
{% for key,value in city_data.items %}
<li>{{ value }}</li>
{% endfor %}

Django ManyToMany two for loops

I have two for loops from which the first one (for i in var) is for getting the posts and the other is for getting the tags (ManyToManyField in the Post model) for that post:
{% for i in var %}
{% for j in i.tags.all %}
{{ j.name }}
{% endfor %}
{% endfor %}
Why won't this work?
EDIT:
Here is what the variables contain:
var:
[<SearchResult: myapp.post (pk='1')>, <SearchResult: myapp.post (pk='2')>]
and here is {{ i.tags }}:
<django.db.models.fields.related.ManyRelatedManager object at 0x1620dd0>
If I try to iterate it with .all it returns nothing.
EDIT 2:
This might be the problem - var is a variable from a SearchQuerySet (django haystack):
var = SearchQuerySet().all()
Inside the template, the j is something like <SearchResult: myapp.post (pk='1')>, which does not have .tags attributes. Try for j in i.object.tags.all, the .object refers the actual Model instance.
Note that Django normally does not complain about trying of accessing non-existing attributes (i.tags here) during template rendering. Hence rendering nothing may also mean incorrect attributes referring.
Solved it by adding the tag field into the haystack searchindex. Now it outputs the list of tags. Thank you all for your help!

Loop over a sorted dictionary a specific number of times in a django template

I have a sorted dictionary that contains sort options:
sort_options = SortedDict([
("importance" , ("Importance" , "warning-sign")),
("effort" , ("Effort" , "wrench" , "effort")),
("time_estimate" , ("Time Estimate" , "time")),
("date_last_completed" , ("Date Last Completed" , "calendar")),
])
I'm displaying these options in my template:
{% for key, icon in sort_options.items %}<!-- Sort Options -->
<a class="btn btn-info" href={{ request.path }}?key={{ key }}&orientation=desc><i class="icon-{{ icon.1 }} icon-large"></i></a>
{% endfor %}
I need to define the 4 sort options, but I only want to display the first 3 (the remaining options are used elsewhere). I also anticipate adding other sort options that I won't need to be displayed. I could write an if statement with a forloop counter to prevent the last option from displaying, but this seems wasteful.
I found this filter but I'm not sure how to combine it with the forloop that needs both the key and the icon data.
How can I write a django template for loop that runs on a dictionary and only loops X number of times?
Similar to Joe's answer, but there's actually a built-in filter slice that'll do this for you:
{% for key, icon in sort_options.items|slice:":3" %}
I think you could do this with a template filter. For example, in:
./mymodules/templatetags/mytags.py
#register.filter
def get_recent(object, token):
"""
Must pass a Option Dictionary
"""
return object.items()[:token]
And then in your template:
{% load mytags %}
{% for option in sort_options|get_recent:3 %}
key: {{ option.0 }}
value: {{ option.1 }}
{% endfor %}
I haven't had a chance to test the above code, but think the logic is sound. Let me know what you think.

Django: Add number of results

I'm displaying the number of search results, however, i do more than one search.
So to display the number of results i'd have to add them up.
So i've tried this:
<p>Found {{ products|length + categories|length + companies|length }} results.</p>
But i get an error.
How do i do this?
Django templates do not support arithmetic operators. However you can use the add filter. I think you need something like this:
<p>Found {{ products|length|add:categories|length|add:companies|length }} results.</p>
Alternatively you should calculate the total in the view and pass it pre-calculated to the template.
EDIT: Further to the comments, this version should work:
{% with categories|length as catlen %}
{% with companies|length as complen %}
<p>Found {{ products|length|add:catlen|add:complen }} results.</p>
{% endwith %}
{% endwith %}
However, this feels very hacky and it would be preferable to calculate the figure in the view.
I would do this in your view when you are creating your context dictionary:
'result_count': len(products) + len(categories) + len(companies)
Then, in your template, just use:
<p>Found {{ result_count }} results.</p>
I'd like to point that Van Gale's answer is not optimal.
From the QuerySet API documentation, you should use query.count() rather than len(query)
A count() call performs a SELECT COUNT(*) behind the scenes, so you
should always use count() rather than loading all of the record into
Python objects and calling len() on the result (unless you need to
load the objects into memory anyway, in which case len() will be
faster).
So the answer should be:
In the view:
'result_count': products.count() + categories.count() + companies.count()
The template remains unchanged

Why is my django view returning a zero obejct list?

I might be lazy or am blind! but the following code is returning ZERO!
items, while very well i know there is some items in the list,
View:
def post_answer(request, quest_id=None):
answer_list = Answer.objects.filter
(questionis__pk=quest_id).select_related()
...
# if a put a print stmt here ( answer_list[0].answer ) there is
# data displayed on the console!!
return render_to_response('myapp/post_answer.html',{'answerobj':answer_list }} )
Template post_answer.html:
{% regroup answerobj.object_list by answer as ans_list %}{{ ans_list|length }}
....
the above code prints 0.
I must be goofing somewhere, pls assist
Paul
try :
{% regroup answerobj by answer as ans_list %}{{ ans_list|length }}
object_list isn't required.