Is it possible to accumulate values with increment in a Django template? - python

I would like to know if there is any way to sum values in a variable in a Django template using {% for obj in objects %}. Something like this:
for student in students:
notes += student.note
Using the mathfilters or something similar to make the sum
Thanks!

If you want sum values in template you can use with tag
please read this link for more information
https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#with

You can use add filter.
It is a not a good idea to do so anyway. You want to keep your logic inside the views and keep the rendering inside the templates.
You can also use django-mathfilters
{% load mathfilters %}
{{ num1 | addition:num2 }}

Related

Django, how to template aggregate responses

I have series of aggregations in DJANGO that I am performing. What I want to know, is if there is a way to {{ template }} a particular row-value from a dataset.
For example: If I have this dataset response from the server:
[{ type:'O', count:54},{ type:'E', count:125},{ type:'C', count:2}]
Can I reference the counts by type in the template without going through the foreach command?
For example: officers: {{ variable.O.count }} or something like that so I can just directly reference the value in a specific row?
The only other option I have right now, is to call the database three times. And I'm hoping not to have to do that.
Thank you.

What is the format when I get data from multiple checkboxs? Can I get a list?

I have a Kind Tag with property tagName, and in a html, I code like this
{% for tag in tags%}
<input type="checkbox" name="tagName" value={{tag.tagName}}>{{tag.tagName}}
{% endfor%}
Now, In my python file, I try to do this:
tagNames = self.request.get('tagName')
I want a list that contain every choice user choose. But what I got seems not.
So.
how can I get a list of user choices using request.get()?
Is there any other ways? I am not familiar with django, I just import gae's template. Can I use gae's template to simplify
this question?
Thank you!
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict
Looks like QueryDict.getlist(key, default) will get you what you want.
ie. self.request.getlist('tagName')
Assuming you're using the webapp framework, instead of self.request.get(), use self.request.get_all('tagName'), which will return a list of values.

Why can't iterate through this list in a Django template

I have a variable from my view that is the output of a Model.objects.all() call on that Model. I'm passing it to my template in my view, and I'm trying to iterate over it in the template. I can access the first element of it simply by this line of code. 'code' is the name of a field in my django model. This line does print the first element's 'code' attribute correctly.
{{ var_name.0.code }}
However, when I try to iterate over var_name in a template for loop, nothing shows up. I tried the following code:
{% for single_var in var_name %}
{{ single_var.code }}
{% endfor %}
This isn't actually what I want to do in the for loop, but getting this to work will let me do what I need in the template. It may be noteworthy to add that at the moment this list has only one element in it.
This is for a work project, so that's why I changed the variable names to something generic.
I found that changing the name of single_var to something without an underscore seemed to fix it. This doesn't make a lot of sense to me because the Django template language documentation states the following:
Variable names consist of any combination of alphanumeric characters and the underscore ("_").
Does anyone know why this seemed to fix the problem?

How can I distinguish lists from strings in django templates

I'm developing a project on Google AppEngine, using Django templates, so I have to use tags like {{ aitem.Author }} to print content within my HTML template.
Author, however, can either be a string or a list object, and I have no way to tell it in advance. When the Author is a list and I try to print it on my template, I get the ugly result of
Author: [u'J. K. Rowling', u'Mary GrandPr\xe9']
Is there any way to handle this kind of scenario (basically printing a field differently depending on its type) effectively? Do I have to rely on custom tags or any other means?
I think the cleanest solution would be to add a method to the model get_authors() which always returns a list either of one or more authors. Then you can use:
Author: {{ aitem.get_authors|join:", " }}
If you for some reason have only access to the templates and can't change the model, then you can use a hack like this:
{% if "[" == aitem.Author|pprint|slice:":1" %}
Author: {{ aitem.Author|join:", " }}
{% else %}
Author: {{ aitem.Author }}
{% endif %}
P.S. it's not a good convention to use capital letters for attribute names.
I think that Aidas's get_authors() solution is the best, but an alternative might be to create a template tag that does the test. You'll want to read up on custom template tags, but they aren't that hard to create if you look at the existing ones.
I followed Matthew's advice and eventually implemented a filter to handle lists.
I'm posting it here just in case someone else needs it.
#register.filter(name='fixlist')
def fixlist(author):
if type(author) == list:
return ', '.join(author)
else:
return author
I call it from the template pages like this {{ aitem.Author|fixlist }}
Thank you for the help!

Django-Tagging - count and ordering top "tags" (Is there a cleaner solution to mine?)

I'm using Django-Tagging, and I don't exactly need a cloud, I just want a limited list of the most popular tags used in my blog entries.
Using the following:
[(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)]
It returns an array (note I'm using Lorem Ipsum while I develop):
[(u'deposit', 5), (u'escorol', 1), (u'gratuitous', 8), (u'marquee', 2)]
But then to order and limit it I need to then do this:
sorted([(tag.name, int(tag.count)) for tag in Tag.objects.usage_for_model(Post, counts=True)], key=lambda k:k[1], reverse=True)[:10]
Is there a neater way to do this? I feel like there must be.
If you are using the latest version of django, you could use aggregation. http://docs.djangoproject.com/en/dev/topics/db/aggregation an example on that page ..
Book.objects.annotate(num_authors=Count('authors')).order_by('num_authors')
Django's {% regroup %} template tag might be useful for this. Assuming tags is in the context of your template:
{% regroup tags|dictsort:"count" by count as sorted_tags %}
...
{% for count in sorted_tags %}
...
{% for tag in count %}
...
{% endfor %}
{% endfor %}
I find the following sorting code a bit more readable than the one you wrote. Of course it doesn't remove the source problem stated by abeyer
import operator
tags = Tag.objects.usage_for_model(Post, counts=True)
tags.sort(key=operator.attrgetter('count'), reverse=True)
If you need to pull all the tags anyway, and the limit to the top n is simply a presentation thing, Fragsworth's answer is probably the way to go. If you aren't using the remainder of the tags somewhere else, I'd argue that this is really something that should be happening in the database query...you would want to be doing an 'ORDER BY count DESC LIMIT n' on the query to avoid pulling a bunch of tags that you aren't going to use.
However, it appears that django-tagging is hard coded to always group/sort by tag ids and names. I'd say the right solution is to file a bug against that, and get an api exposed that will give you back the top n tags.
I use raw sql for this:
trends = Tag.objects.raw("select tagging_tag.id, count(object_id) as counter from tagging_tag left join tagging_taggeditem on tagging_tag.id = tagging_taggeditem.tag_id group by tagging_tag.id order by counter DESC limit 10")
My approach for getting top tags in Django-Tagging is:
top_tags = Tag.objects.annotate(num=Count('taggit_taggeditem_items')).order_by('-num')

Categories

Resources