How do I auto increment my results in a page? - python

I made this table but I can't figure out how to do the numbering. I want a top 10 list and I get all the data from a database. I essentially want to make it show '1' and the next '2' and the next '3' and so forth. How would I able to do this?
https://imgur.com/a/9Isf941
def home(request):
straatData = data.objects.all()[:10]
count = data.objects.count()
numbers = []
for dataCount in range(1, count + 1):
numbers.append(dataCount)
context = {
'data': straatData,
'count': numbers,
}
return render(request, 'home.html', context)
I need to get the top numbers to show 1,2,3,4... as many as the results. But I don't know how to do it

You don't need to set a context variable for that. You can use forloop.counter in your template code.
{% for item in data %}
<tr>
<td> {{ foorlop.counter }} </td>
<td> {{ item }} </td>
</tr>
{% endfor %}
If you want to start counting at 0, use forloop.counter0

Perhaps you should be using jinja to render the table in a loop?
In your html:
{% for num in count %}
<tr>
<td> {{ num }} </td>
<td> {{ data[num][0] }} </td>
<td> {{ data[num][1] }} </td>
<!-- Im not sure how your data is formatted! -->
</tr>
{% endfor %}
Without seeing your html it's hard to know how you're currently rendering the table.

Related

multiple python lists to table rows in HTML

I have multiple lists created in python. I am trying to convert these lists into HTML rows.
week = ['1','2']
date = ['2022-10-01','2022-10-09']
My HTML table should look like below:
Week Date
1 2022-10-01
2 2022-10-09
what I tried so far:
{% for val in data %}
<tr>
<td>
{% for item in val.week %} {{ item }} <br> {% endfor %}
</td>
<td>
{% for item in val.date %} {{ item }} <br> {% endfor %}
</td>
</tr>
{% endfor %}
The problem with above code is every value is treated as cell instead of row and hence I am unable to apply any row related styles to the above.
Could someone help with how to convert these to rows instead of cells.
Thank you.
You can use dictionary comprehension to convert the two lists into a dictionary where the key would be the week number and the value would be the corresponding date. You can loop over the dictionary as key and value using the items attribute in the template.
# views.py
week = [1, 2]
date = ['2022-10-01','2022-10-09']
data = {week[i]: date[i] for i in range(len(week))}
return render(request, 'template.html', {'data': data})
# template.html
{% for key, value in data.items %}
<tr>
<td> {{ key }} </td>
<td> {{ value }} </td>
</tr>
{% endfor %}
try this approch...
------ views.py ------
week = ['1','2']
date = ['2022-10-01','2022-10-09']
data = tuple(zip(week,date))
------ html ------
<table style="border: 1px solid; border-collapse: collapse;">
<thead>
<th>Weeks</th>
<th>Dates</th>
</thead>
<tbody>
<tbody>
{% for i,j in data %}
<tr>
<td>{{i}}</td>
<td>{{j}}</td>
</tr>
{% endfor %}
</tbody>
</tbody>
</table>
-------- Output -------

How to Reassign value to variable in Django template through filters

I have an xml object that I am looping to print in template. It is detailing of items with their tax rate. so after printing all items I need sum of those tax rate values. I am trying to sum up that value in template. I have created filter named updatevariable, it is working and doing sum up but issue is due to loose of old sum it just returns latest value rather than whole sum up. SO I need a way to reassign TotalTax with sum up value from filter.
this is example of output needed:
Tax-1 16
Tax-2 18
Tax-3 2
TotalTax = 36
{% with TotalTax=0 %}
{% if taxRateDetailing %}
{% for item in taxRateDetailing%}
<tr>
<td>
{{item.1.text}}
</td>
<td>
{{item.4.text}}
{{TotalTax|updatevariable:item.4.text}}
</td>
</tr>
{% endfor %}
<tr>
<td>
Total Tax
</td>
<td>
{{TotalTax}}
</td>
</tr>
{% else %}
<tr>
<td>
Tax
</td>
<td>
{{defaultSalesTaxRate}}
</td>
</tr>
{% endif %}
{% endwith %}
Filter function
def updatevariable(value, arg):
TotalTax = value + float(arg)
return TotalTax

Using Flask and WTForms how can i have a table where some columns are inputs?

I'm struggling to see how this is done, and the documentation doesn't seem to help much.
I need to generate a table, the row size will be variable, but not dynamic (i know how much rows i need before generating the page).
For the sake of simplicity lets imagine a page where you grade n exams with an integer.
i tried this:
the form.
class InputInteger(Form):
grade = IntegerField('Grade')
the view
#decorator..
def grade():
form = InputInteger()
names = student_list
return render_template("grade.html", form=form, names=names)
the template
<table>
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
{% for name in names %}
<tr>
<td>
{{name}}
</td>
<td>
{{form.grade}}
</td>
</tr>
</table>
But how do i read back the inputed values?
How do i distinguish who's grade that belongs too?
Am fairly confused, i've read about FieldList(FormField(IntegerField)), but isn't that just one field with a list of integers?
What about the Table Widget, do i need that?
Please help.
For anyone looking at this now, the OP was correct to think about FieldLists and FormFields. Here is a solution:
forms.py:
class GradeForm(FlaskForm):
student = IntegerField('Student ID')
grade = IntegerField('Grade')
delete = BooleanField('Delete')
class GradeFormSet(FlaskForm):
gradeset = FieldList(FormField(GradeForm), min_entries=0)
view.py:
def grade():
# create a dict of student IDs and their initial grades (or None for now)
init_merits = [dict(student=s.id, grade=None) for s in myStudentTable.query.all()]
gradeform = GradeFormSet(gradeset=init_merits)
if form.validate_on_submit():
...
# meritforms.data['gradeset'] contains a list of dictionary values for further processing
# check 'delete' == True to handle deletion of that student from your table
...
return render_template('template.html', form=gradeform)
Template:
<table>
{% for merit in form.gradeset %}
<tr>
<td>{{ merit.placing(readonly=true) }} {{ merit.csrf_token }} {{ merit.hidden_tag() }}</td>
<td>{{ merit.grade }}</td>
<td>{{ merit.delete }}</td>
</tr>
{% endfor %}
</table>
<input type="submit" name="finish" value="Save">
<input type="submit" name="cancel" value="Cancel">
You're almost right. Put your table inside a html form and catch in a function where you can retrieve your input fields.
Here is an example:
<form action="/grade">
<table>
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
{% for name in names %}
<tr>
<td>{{name}}</td>
<td><input id='{{name}}' value='{{ form.grade }}'></td>
</tr>
</table>
</form>
And your Flask function:
#app.route('/grade', methods=['GET', 'POST'])
def grade():
if request.method == 'POST':
return 'Form posted.'
When you post your form to your function, you can access your input field by this way: request.form['inputfieldname'] and then you do your stuff. I hope my explanation is clear.

Django For loop template for dict data

So in Python if i have a Dictionary rather than a list with a dataset, I would normally call (for example):
for i in myDictionary:
myDictionary[i]['event']
myDictionary[i]['timestamp']
etc.
But in Django this does not work:
{% for i in myDictionary %}
<tr>
<td> {{ myDictionary.i.event }}</td>
<td> {{ myDictionary.i.timestamp }}</td>
</tr>
Does not produce results - what's the optimal way to handle dictionaries with an arbitrary number of keys?
You have a weird structure. What you want is a list of dictionaries.
myDicts = []
for i in myDictionary:
data = {'event': '...', 'timestamp': '...'}
myDicts.append(data)
Then, you can loop over dictionary values by using the function .items, like in a normal loop (but don't include the parenthesis):
{% for elem in myDicts %}
{% for key, value in elem.items %}
<tr>
<td> {{ myDictionary.key }}</td>
<td> {{ myDictionary.value }}</td>
</tr>
{% endfor %}
{% endfor %}

How to show sorted list by overall completion in Pootle

Hi I am new to Django and working on Pootle project.
I would like to sort by Overall completion by default in the pootle index page.
for example, http://pootle.locamotion.org/ lists the languages and sorted by names. you can click sort buttons to see sort by completion. but I would like to show this list sorted by completion whenever load a page.
in pootle/local_apps/pootle_app/templates/index/index.html,
<table class="sortable">
<tr>
<th>{% trans 'Language' %}</th>
<th>{% trans 'Overall Completion' %}</th>
<th>{% trans 'Last Activity' %}</th>
</tr>
{% for item in languages %}
{% ifnotequal item.total 0 %}
<tr class="{% cycle 'even' 'odd' %}">
<td class="language">
{{ item.name }}</td>
<td>
<div class="sortkey">{{ item.transper }}</div>
<div class="graph" title="{{ item.completed_title }}" dir="{% if LANGUAGE_BIDI %}rtl{% else %}ltr{% endif %}">
<div class="translated" style="width: {{ item.transper }}px"></div>
{% if item.fuzzy %}
<div class="fuzzy" style="{%if LANGUAGE_BIDI%}right{%else%}left{%endif%}: {{ item.transper }}px; width: {{ item.fuzzyper }}px"></div>
{% endif %}
{% if item.untrans %}
<div class="untranslated" style="{% if LANGUAGE_BIDI %}right{% else %}left{% endif %}: {{ item.transper|add:item.fuzzyper }}px; width: {{ item.untransper }}px"></div>
{% endif %}
</div>
</td>
<td>{{ item.lastactivity }}</td>
</tr>
{% endifnotequal %}
{% endfor %}
</table>
item.transper is the key that I want to sort by.
and this is how item and language is defined:
def get_items(request, model, get_last_action, name_func):
items = []
if not check_permission('view', request):
return items
for item in model.objects.iterator():
stats = item.getquickstats()
stats = add_percentages(stats)
lastact = get_last_action(item)
items.append({
'code': item.code,
'name': name_func(item.fullname),
'lastactivity': lastact,
'trans': stats["translatedsourcewords"],
'fuzzy': stats["fuzzysourcewords"],
'untrans': stats["untranslatedsourcewords"],
'total': stats["totalsourcewords"],
'transper': stats["translatedpercentage"],
'fuzzyper': stats["fuzzypercentage"],
'untransper': stats["untranslatedpercentage"],
'completed_title': _("%(percentage)d%% complete",
{'percentage': stats['translatedpercentage']}),
})
items.sort(lambda x, y: locale.strcoll(x['name'], y['name']))
return items
def getlanguages(request):
def get_last_action(item):
try:
return Submission.objects.filter(translation_project__language=item).latest()
except Submission.DoesNotExist:
return ''
return get_items(request, Language, get_last_action, tr_lang)
what should I change this so that I see sort by Overall Completion by default?
thank you so much for any suggestions
Change
items.sort(lambda x, y: locale.strcoll(x['name'], y['name']))
to
items.sort(lambda x, y: cmp(x['transper'], y['transper']))
(This works well with the builtin cmp function because the transper fields are converted to ints by the nice_percentage function, which is called as part of add_percentages)
If that doesn't produce the order you wanted, simply switch objects x and y.
If instead you need to sort it in the template (it's typically a bad idea to mess with third-party apps' source code), you can use the dictsort filter:
{% for item in languages|dictsort:"transper" %}
Again, if that's not the order you wanted, use dictsortreversed.
The latest development version of Pootle, to become Pootle 2.2, now remembers which column you have selected to sort on. So a page reload will now remember the order you last used.

Categories

Resources