Trouble converting number from query result to float in the template - django

i have an sql stored procedure returning me values (Characteristics and their value).
The values are real in the table, fixed to 2 decimals, the table doesn't seem to be the problem since the numbers are stored properly.
The problem come when i load my template (i use Python+Django), those value are listed in a tab :
<table id="regnorme3Tab" name="regnorme3Tab" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Code</th>
<th style="width:200px">Libellé</th>
<th>Limite inf</th>
<th>Valeur</th>
<th>limite sup</th>
</tr>
</thead>
<tbody>
{% for reg_norme in reg_savs %}
{%if reg_norme.Saisie == 'O' %}
<tr name="Reg_Normes" id="{{reg_norme.regauxnormes}}">
<th><span> {{reg_norme.Id}}</span></th>
<th class="codevalue"><span> {{reg_norme.Code}}</span></th>
<th style="width:200px"><span> {{reg_norme.LibEtendu}}</span></th>
<th><span> {{reg_norme.LimitInf}}</span></th>
<th><span><input type="number" max="{{reg_norme.LimitSup}}" step="0.01" min="{{reg_norme.LimitInf}}"class="{{reg_norme.Code}}" id="{{reg_norme.Id}}" value="{{reg_norme.Valeur}}" required style="width:40px;"></span></th>
<th><span> {{reg_norme.LimitSup}}</span></th>
</tr>
{%endif%}
{% endfor %}
</tbody>
</table>
If i leave things like that, nothing is displayed in my input, i had the same problem on some isolated number input and i managed to display the data by using parseFloat() and toFixed(2).
document.getElementById('ebHumValue').value = parseFloat({{displayHUMHumidite}}).toFixed(2);
So i though i would create a function with a loop on my tab and use parseFloat and toFixed to display something.
$("#regnorme3Tab :input").each(function () {
var number = this.name;
this.value = number;
alert(parseFloat(this.name).toFixed(2));
});
The function is in document.ready so it would format the number correctly after loading.
But the problem is that i doesn't work in the tab, i tried to display the value at different stage, for reason i don't understand first it change from like 22.4 (in the table) to 22.3999945754 when i print it, when i use parseFloat() on it, it become 22 and even if i use toFixed(2) with it, it become 22.00 and i don't really get why since the same conversion on isolated input work on my page.
Any idea why the base value get changed like that in the first place ? And how i can manage to cast that so it would display the correct number ?

Hi have you tried to use the template gabarit floatformat builtin ?
{{ displayHUMHumidite |floatformat:2 }}
source here : https://docs.djangoproject.com/fr/2.0/ref/templates/builtins/#floatformat

Related

executing python script in django with arguments from the frontend

I want to manipulate the values associated with the entries of an external mongodb database using a django webapp.
I've created the app and I'm currently displaying all the entries and their associated value in a simple table.
My idea is simply to create a button, that calls a python script with an argument (the id of that entry) and then changes it from false to true. The problem is, this seems like rocket-science, I've been at this for days now and I just can't get it to work as I have little to no proficiency when it comes to Ajax or Jquery, and all relevant examples I can find don't simply seem to pertain very well to my situation despite how basic it would appear, nor fit with Django 2.0+.
I'm using Django 2.1.5
def change_value(idnumber):
db_value = get_db_status_value(idnumber)
if db_value is True:
change_db_entry_status(idnumber, False)
else:
change_db_entry_status(idnumber, True)
my_template.html
<table>
<thead>
<tr>
<th> Status </th>
<th> Button </th>
</tr>
</thead>
<tbody>
{ % for entry in entry_data % }
<tr>
<td> {{ entry.status }} </td>
<td> <button type="button">{{ entry.idnumber }}</button> </td>
</tr>
</tbody>
{% endfor %}
</table>
I simply can't figure out how I can get the change_value function in there that I can create a button for and include an argument ( entry.idnumber ). This seems incredibly difficult, which from what I understand is a design principle, but it seems a shame if I can't even accomplish something as basic as above.
I was hoping someone could explain how I'm actually supposed to go about this? So far, it seems I require AJAX or Jquery (unfortunately, I barely know the basics of this, and what usually trips me up is that the urls.py which exist in both project and application level seems to work a little different in django 2.0+ compared to older versions)
This isn't actually difficult. It's just that you're missing an understanding of the relationship between the client and the backend code.
Once the template is rendered, the user sees it as HTML in their browser. That's it as far as the backend (ie Django) is concerned. The only way to run any further code on the server is to send another request. A request involves the browser contacting the server, which requires a URL and a view in Django.
Now, one way to send that request is via Ajax, but for your purposes that isn't necessary; since you're just learning, it's easier if you make it a simple form. So, your template might look something like this:
{% for entry in entry_data % }
<tr>
<td> {{ entry.status }} </td>
<td><form action="{% url 'change_value' idnumber=entry.idnumber %}" method="POST"> {% csrf_token %} <button type="submit">{{ entry.idnumber }}</button> </form></td>
</tr>
{% endfor %}
</tbody>
Notice how every iteration of the for loop has a separate form, which posts to a specific URL including the ID number.
Next you need a URL:
path('change_value/<int:idnumber>/', views.change_value, name='change_value'),
and update your function to actually be a view, which needs to accept a request and return a response:
def change_value(request, idnumber):
if request.method != "POST":
return HttpResponseNotAllowed()
db_value = get_db_status_value(idnumber)
if db_value:
change_db_entry_status(idnumber, False)
else:
change_db_entry_status(idnumber, True)
return redirect('/')
You always need to redirect after a POST, but you could redirect back to the same URL that rendered my_template in the first place. (Also note I've put in a test to make sure the user is actually sending a POST; you don't want Google to crawl this URL and flip your values for you.)
And that's it, now you have a button that should toggle your value.
The answer from #Daniel is enough for you. But if you want to use ajax so that the page does not have to refresh to change the vaue, you may do something like:
In your template make changes as:
<table>
<thead>
<tr>
<th> Status </th>
<th> Button </th>
</tr>
</thead>
<tbody>
{ % for entry in entry_data % }
<tr>
<td id="status"> {{ entry.status }} </td>
<td> <button type="button" onclick="change_status(this)" id="{{ entry.idnumber }}">{{ entry.idnumber }}</button> </td>
</tr>
</tbody>
{% endfor %}
and a script as:
<script>
function change_status($this){
var request_data = $this.id;
console.log("data: " + request_data);
$.post({
url: "url that leads to your view",
data : { request_data: request_data},
success : function(json) {
document.getElementById('status').innerHTML = "" //insert the data returned from the function
}
})}
</script>

Nested table rows in Vue

There has been several versions of this question, but I've found a specific scenario I can't get my head around. I have this template on a parent element:
<tbody>
<tr is="tree-item" v-for="item in children" :item="item"></tr>
</tbody>
So far so good. The child element is:
<tr v-on:click="toggle" class="{{ classes }}">
<td class="name">
{{ item.tree_item_heading }}
</td>
</tr>
<tr v-show="isLoaded" is="tree-item" v-for="item in grandChildren" :item="item"></tr>
It's a recursive form line, so if the first tree-item has children, they will render as tree-item too. Although it shows up fine, it is rendered as a Fragment Instance, hence the v-show property gets ignored.
Any idea on how to solve this?
Cheers
You could try using multiple tbody tags for your parent loop:
<tbody v-for='item in children'>
<tr is="tree-item" :item="item"></tr>
<tr v-show="isLoaded" is="tree-item" v-for="gItem in item.children" :item="gItem"></tr>
</tbody>

Display ColdFusion Query Output in a Formatted Table

Let me begin by saying that I'm a novice at ColdFusion and trying to learn so please bear with me.
I work in an apartment complex that caters to students from the local college. We have one, two and four bedroom apartments. Each room in an apartment is leased to an individual student. What I want to do is populate an HTML table with all the people in a room. My query is working and pulling all the relevant data but what is happening is that each person is being split out to their own HTML table instead of all the people in a room being put into the same table. Here is an example:
What I want
What is happening:
Here is my code:
<!---Begin data table--->
<cfoutput query = "qryGetAssignments">
<div class="datagrid">
<table>
<tr><td align="right"><strong>#RoomType#</strong></td></tr>
<thead>
<tr>
<th>#RoomNumber#</th>
</thead>
<tbody>
<tr><td><strong>#Bed#</strong>
| #FirstName# #LastName# :: #StudentNumber#
</td>
</tr>
</tbody>
</table>
</div>
</cfoutput>
I know why the output is coming out like it is, I just don't know how to fix it. I want there to be four residents in one table for a four bedroom apartment, two residents in a table for a two bedroom, and so on. Thanks in advance for your help.
Edit:
Sorry about the confusion. Here is a full pic of what I'm going for:
This should do what you need, assuming your query is properly ordered by roomType, for the <cfoutput group=""> to work.
<!---Begin data table--->
<cfoutput query="qryGetAssignments" group="roomType">
<div class="datagrid"><!--- If this isn't needed to style the tables, it can be moved outside the loop --->
<table>
<tr><td align="right"><strong>#qryGetAssignments.roomType#</strong></td></tr>
<thead>
<tr>
<th>#qryGetAssignments.roomNumber#</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<strong>#qryGetAssignments.bed#</strong>
<cfoutput><!--- this output here will loop over rows for that groupby --->
| #FirstName# #LastName# :: #StudentNumber#
</cfoutput>
</td>
</tr>
</tbody>
</table>
</div>
</cfoutput>
I've also scoped your query variables, at least I believe they are variables from a query.
That should work except it might need to be grouped by "roomNumber" such as N108.

django and dataTables - speed up query and page display

I have a page in my app that lists all our client records - about a thousand total. The query is straight forward (two queries, actually) and look like this (one for commercial and one for residential):
all_comm = System.objects.all().filter(isRessy=False)
all_ressy = System.objects.all().filter(isRessy=True)
In my template, I simply iterate over both queries displaying the information in a table. This code looks like this:
<table style="width:100%;" class="field_container dt full-border">
<thead>
<tr>
<th align=left width=200>Owner</th>
<th align=center width=100>System ID</th>
<th align=left>System Address</th>
<th align=center width=200>Options</th>
</tr>
</thead>
<tbody>
{% for System in all_ressy %}
<tr onclick="window.location.href='{% url cpm.systems.views.system_overview System.systemID %}'">
<td>{{ System.billingContact.lastName }}, {{ System.billingContact.firstName }}</td>
<td align=center>{{ System.pk }}</td>
<td>{{ System.systemAddress }}, {{ System.systemCity }}</td>
<td align=center>
Create Service Call
</td>
</tr>
{% endfor %}
</tbody>
</table>
This code is identical for showing all the commercial records. If you'll notice that I have a class of dt listed in the table. That sets the table to be a dataTable table. As such, the rows get nice highlighting, the columns can be sorted, and there's a search box at the top of the table. All nice stuff.
The problem is that the page, as a whole, is a bit slow to load. It seems that half of the loading time is the raw displaying of data (fetching data then iterating over all the records generating the basic HTML table). The second half of the loading time (or at least a decent chunk of the time) looks to be devoted to converting the regular table into a dataTable.
I'm wondering if there's anything I can do to speed this whole process up. I've tried using pagination on the dataTable but that seems to be useless since all the records are loaded anyway, just hidden across multiple dataTable pages. Real pagination for the whole page isn't really possible given the nature of the app. I feel like the queries aren't going to get any faster so there's got to be optimization or some trick to make this page load faster.
Any thoughts?
Thanks for the help
Edit I'm referring to this dataTable plugin: http://datatables.net/index
You could try using ajax to load the data directly into the DataTable It would remove the HTML rendering step.
http://datatables.net/release-datatables/examples/ajax/objects.html (I assume this is the datatables you are talking about...)

sending html to django template from view

I am new to django so I may be going about this the wrong way (pretty sure I am).
Trying to get a webpage to display data from a postgresql DB in a table showing a status for a list of servers.
This is part of the template
<div class"row"=""><div class="span3" style="background-color:lightyellow; margin-left:20px">
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th>Server</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{{ res }}
</tbody>
</table>
</div></div>
In my view I have this,
message = []
for res in data:
message.append(" <tr>")
message.append(" <td>" + str(res).split("'")[1] + "</td>")
if str(res).split("'")[3] == 'No':
message.append(" <td><FONT COLOR=\"008200\">Available</FONT> </td>")
else:
message.append(" <td><FONT COLOR=\"FF0000\">Down</FONT> </td>")
message.append(" </tr>")
return render_to_response('health.html', {'res':message}, context_instance=RequestContext(request))
If I print that instead of doing the append I get the resulting HTML I would expect.
As it currently is, I don't get anything displayed on the webpage in that table.
I don't expect it to render the list necessarily, but would have thought something should have showed up in the table even if it was incorrect format.
Should this HTML processing be done in the template and not the view?
Yes, it is usually best to do all HTML processing in the template. This way you can separate your database access logic from your display logic and thereby reduce coupling. It also means you can easily re use template.
So you should use the view function to get the appropriate objects and pass them to the template as variables.
Still, you are sort of on the right track. In order for your {{res}} variable to display properly I think you will need to change the template to.
<tbody>
{% for message in res %}
{{ message }}
{% endfor %}
</tbody>
This should iterate over the elements in the res variable which you passed to the template.