My data are like this :
13.2610136284,20.8676059554,11.6376896892,0.51203356592,167,20154.4815106,
395,766,56,55047.3477967,-26818.1766435,3072.97868784,12.5402166873,-1443.
74556748,-4.0
I need to display it as a table in html
This is the function used in python to transform the data suitable for a table
import string
from datetime import datetime, date
def ratio_fil():
ratioFil = open('sergRatiosOut20170426','r')
rat = ratioFil.read().split(',')
ratioFil.close()
return rat
Rat is similar to this :
['13.2610136284', '20.8676059554', '11.6376896892', '0.51203356592',
'167', '20154.4815106', '395', '766', '56', '55047.3477967',
'-26818.1766435', '3072.97868784', '12.5402166873', '-1443.74556748',
'-4.0\r\n']
I need to put it in a table, So i create a data_table tags :
<tr><td>X</td>
<td>{{data_table.0|floatformat:1}} %</td></tr>
<tr><td>y</td>
<td>{{data_table.1|floatformat:1}} %</td></tr>
<tr><td>y1 </td>
<td>{{data_table.2|floatformat:1}} </td></tr>
<tr><td>y2</td>
<td>{{data_table.3|floatformat:1}} </td></tr>
In Html :
<div> {% with rat as data_table %}
{% include 'tags/data_table.html' %}
{% endwith %}
</div>
The table appears empty, i think it should be a method to import rat ? Please i need your help
You can use builtin for loop template tag to loop through and render the data in HTML table
<table>
<tr>
<th>Column Name</th>
</tr>
{% for data in data_table %}
<td>
<td>{{ data }} </td>
</td>
{% endfor %}
</table>
Remember to return the data from your view
def ratio_fil():
ratioFil = open('sergRatiosOut20170426','r')
rat = ratioFil.read().split(',')
ratioFil.close()
return render(request, 'template_name.html', {'data_table': rat})
Related
I have this page that lists various info on a specific stock including orders that have been placed on that specific item. I would like to display how much money the user of this system would get from that specific order.
<table class='table'>
<thead>
<tr>
<th>ORDER ID</th>
<th>NAME</th>
<th>AMOUNT ORDERED</th>
<th>REVENUE</th>
<th>ORDERED ITEM</th>
<th>ADDRESS</th>
<th>CITY</th>
</tr>
</thead>
{% for x in queryset2 %}
<tr>
<td>{{x.id}}</td>
<td>{{x.name}}</td>
<td>{{x.quantity}}</td>
<td>{{x.quantity * stock.ppu}}</td>
<td>{{x.order_item}}</td>
<td>{{x.address}}</td>
<td>{{x.city}}</td>
</tr>
{% endfor %}
</table>
I have this code so far. What would be the correct syntax to multiply these two variables together : {{x.quantity * stock.ppu}}
You can not write arithmetic expressions in a Django template. You should write this in the view, for example by annotating the queryset:
from django.db.models import F
# …
queryset2 = queryset2.annotate(
total_value=F('quantity') * F('ppu')
)
then in the template you render this as:
<td>{{ x.total_value }}</td>
To do math operations in the Django template you can use this django-mathfilters
but if you try to use a built-in way to do, can follow this to add and Subtraction
Example:
{{x.quantity | add: stock.ppu}}
to do multiplication and division you can use widthratio
Example:
a*b use {% widthratio a 1 b %}
a/b use {% widthratio a b 1 %}
from this answer
or you can make your own custom tags
for add
#register.filter
def add_value(value, arg):
return value + arg
for subtract
#register.filter
def subtract(value, arg):
return value - arg
then use them in your template like this
{{x.quantity | subtract: stock.ppu}}
I created a table in my html file for my Django project, and the raw data is based on the following list (It's a very long list, so I only list a few lines):
mylist=
[{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
...
{'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}]
My Html file:
<table class="table table-striped" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>StartDate</th>
<th>ID</th>
<th>Name</th>
<th>Days</th>
</thead>
<body>
{% for element in mylist %}
<tr>
<td>{{ element.StartDate}}</td>
<td>{{ element.ID }}</td>
<td>{{ element.Receiver }}</td>
<td>{{ element.Days }}</td>
</tr>
{% endfor %}
</tbody>
</table>
I want to make all the rows with the same ID value the same color. Please advise what I should add into the <td>{{ element.ID }}</td>. Thank you!
parts of my views.py:
client = gspread.service_account_from_dict(creds)
def CreateSheet(Return_record):
sheet = client.open(Return_record).sheet1
return sheet
from sheet2api import Sheet2APIClient
sheet = client.open('Return Record 2022')
sheet_instance = sheet.get_worksheet(0)
mylist = sheet_instance.get_all_records()
mylist
def table2022(request):
return render(request,'table2022.html',{'mylist':mylist})
Everything we want to pass as context, we should keep inside view we want to use it in. It's more readable when we have more and more code.
What we are going to do, it's define a color for numbers 0-9. I'll pick some light colors for now, you can change them as you prefer.
views.py:
def table2022(request):
mylist = sheet_instance.get_all_records()
colors = {'0': 'aqua', '1': 'beige', '2': 'burlywood', '3': 'lightgrey', '4': 'silver', '5': 'skyblue', '6': 'lightblue', '7': 'lightpink', '8': 'lightgreen', '9': 'lawngreen'}
context = {'mylist': mylist, 'colors': colors}
return render(request, 'table2022.html', context)
Now, because in templates it's not that simple to use Python, we need to create custom Template Tag. Let's start with creating folder in your app, let's name it custom_tags.py. It should be created in YourProject/your_app/templatetags/ folder, so we have to also create templatetags folder in there.
custom_tags.py:
from django import template
register = template.Library()
#register.filter(name='get_color')
def get_color(colors, number):
return colors[str(number)[-1]]
your_template.html:
{% load custom_tags %}
...
{% for element in mylist %}
<tr>
<td>{{ element.StartDate }}</td>
<td style="background-color: {{ colors|get_color:element.ID }}">
{{ element.ID }}
</td>
<td>{{ element.Receiver }}</td>
<td>{{ element.Days }}</td>
</tr>
{% endfor %}
get_color tag is basically taking whole ID, then extract only last number and make it a string. After that it uses the single number as a key in colors dictionary and passes corresponding value to template, where it is going to be a valid html color.
Custom tags are used to 'implement' some Pythonic code directly into template. Don't use it too much, because most of coding should be in standard files like views.py and models.py. But sometimes there is no better way. :)
For more details about Tags, check that Django's DOCS
I'm using jinja2 and python.
Everything works but a table printed based on a string of arrays, this is the template
<table>
<tr>
<th> {{table.title}}</th>
</tr>
<tr>
{% for value in table.values %}
<td> {{ value }} </td>
{% endfor %}
</tr>
</table>
Table is defined in data in the pyton:
data['table'] = {
'title': 'Title',
'values': ['test','test2']
}
templateVars = data.copy()
templateEnv = jinja2.Environment(
loader=jinja2.FileSystemLoader(f'{package_directory}/assets/templates/'))
outputText = template.render(templateVars)
When executing I get an error:
{% for value in table.values %}
TypeError: 'builtin_function_or_method' object is not iterable
I can't find the error, because I created a list, and it should be iterable. I copied the same code to python and it works.
I solved my problem, it was I was using "values" as key and it's a reserved word, changing it for table_rows it works
I have been searching for a way to make a django template which can show more than 2 values per row in a table,
Let's say I have an class with 5 attributes, and I want these attribute values presented in a table on my HTML page. at first I tried with a dictionary but just 2 of the 5 attributes is not enough.
Lets say my object is like:
class ModelA(models.Model):
ID = models.IntegerField(primary_key=True, db_column='ID')
name = models.CharField(max_length=60, db_column='name')
yesorno = models.CharField(max_length=9, db_column='yes/no')
text = models.TextField(db_column='text')
description = models.TextField(db_column='description')
Now in a view I call for all these model attributes, in what datastructure should I save everything and how can I put all these 5 attributes in one row per object in a table.
(sometimes hundreds of objects may need to be shown in table (so, 100 rows))
Grab all the objects (filter accordingly).
As #init3 points out the ID is not required as Django adds that automatically, and yesorno should be a Bool.
# view.py
model_as = []
for id in ids:
try:
model_a = ModelA.objects.get(ID=id)
except ModelD.DoesNotExist:
# No model found
pass
else:
model_as.append(model_a)
return render_to_response('template.html',
{'model_as': model_as},
context_instance=RequestContext(request))
Loop over the objects in the template and print each variable in whichever column you want.
# template.html
<table>
{% for model_a in model_as %}
<tr>
<td>
{{ model_a.ID }}
{{ model_a.name }}
{{ model_a.yesorno }}
{{ model_a.text }}
{{ model_a.description }}
</td>
<tr>
{% empty %}
<tr>
<td>No ModelAs to see here</td>
<tr>
{% endfor %}
</table>
I am working on a site that will be used to clean up inactive Tableau workbooks. Logging into this site will allow my users to see their old workbooks and decide which ones to keep.
This is going to be accomplished by taking some simple text input from an HTML page, K for keep | D for delete.
The response from the user will then be stored as a Python variable that will go into an if then statement. The if then statement will basically update each row in SQL, adding either K or D to a column called "Marked_for_Deletion".
From there, a stored procedure will run, check that column, and delete all things marked with a D.
Is this feasible? If so, how would I go about pulling that input and making sure it gets added to the right column/row? If not, can you offer any suggestions on a substitute method I can use?
Thanks!
Edit: Here is the code for my table.
<table class="blueTable">
<thead>
<tr>
<th>Workbook Name</th>
<th>Deletion Deadline</th>
<th>Keep or Delete?</th>
</tr>
</thead>
<tbody>
{% for book in Workbooks %}
<tr>
<td>{{ book.name }}</td>
<td>{{ book.owner_name }}</td>
<td>
<label class="container" style="margin-bottom: 25px">
<input type="text" placeholder="(Enter K for Keep, D for Delete)">
</label>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<form method="post">
{% csrf_token %}
<button type="submit" name="run_script">Submit</button>
</form>
</body>
</html>
I want to be able to pull the input from the last td tag and store it with the submit button below there.
I'm kind of late, but I hope it helps you out.
urls.py
from django.urls import path
from workbook_app import views
app_name = 'workbook_app'
urlpatterns = [
path('books/', views.BookListView.as_view(), name='books'),
path('keep_or_delete/<int:pk>/', views.KeepOrDeleteView.as_view(), name='keep_or_delete'),
]
models.py
from django.db import models
class Book(models.Model):
name = models.CharField(max_length=250)
owner_name = models.CharField(max_length=250)
marked_for_deletion = models.BooleanField(default=False)
views.py
from django.views.generic import ListView
from workbook_app.models import Book
from django.http import HttpResponse, HttpResponseRedirect
from django.views import View
from django.urls import reverse
class BookListView(ListView):
template_name = 'workbook_app/books.html'
def get_queryset(self):
return Book.objects.all()
class KeepOrDeleteView(View):
def post(self, request, pk):
book = Book.objects.get(pk=pk)
print(book, book.marked_for_deletion, not book.marked_for_deletion)
book.marked_for_deletion = not book.marked_for_deletion
book.save()
url = reverse('workbook_app:books')
return HttpResponseRedirect(url)
books.html
<div class="container">
<h2>Books</h2>
<table class="table">
<tr>
<th>Workbook Name</th>
<th>Deletion Deadline</th>
<th>Keep or Delete?</th>
</tr>
{% for book in object_list %}
<tr>
<td>{{book.name}}</td>
<td>{{book.owner_name}}</td>
<td>
<form action="{% url 'workbook_app:keep_or_delete' pk=book.pk %}" method="POST">
{% csrf_token %}
<button type="submit" class="btn btn-{%if book.marked_for_deletion %}primary{% else%}danger{% endif %}">{%if book.marked_for_deletion %}Keep{% else%}Delete{% endif %}</button>
</form>
</td>
</tr>
{%endfor%}
</table>
P.S. I'm not handling exceptions, messages, etc. You're just gonna have to figure it out yourself or open a new question.