Finding the sum of numbers in jinja2 template using flask - python

I am learning flask and tried to create a web app that accepts a student's name and marks, finds the total of all the marks and display things in a table. But the total always gets displayed as 0.
The code is given below
mark_total.py:
from flask import Flask, render_template, request
app = Flask (__name__)
#app.route('/')
def student():
return render_template('student.html')
#app.route('/result', methods = ['POST', 'GET'])
def result():
if request.method == 'POST':
result = request.form
return render_template('result.html', result = result)
if __name__ == '__main__':
app.run(host = '0.0.0.0', debug = True)
student.html:
<form action = "/result" method = "POST">
<p>Name <input type = "text" name = "Name" /></p>
<p>Physics <input type = "text" name = "Physics" /></p>
<p>Chemistry <input type = "text" name = "chemistry" /></p>
<p>Maths <input type ="text" name = "Mathematics" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
result.html:
<html>
<head>
<title>Results</title>
</head>
<body>
<h1>{{result["Name"]}}'s results</h1>
{% set total = 0 %}
<table border = 1>
{% for key, val in result.iteritems() %}
{% if key != 'Name' %}
{% set total = total|int + val|int %}
<tr>
<td>{{ key }}</td>
<td>{{ val }}</td>
<td>{{ total }}</td>
</tr>
{% endif %}
{% endfor %}
<tr>
<td>Total</td>
<td>{{total}}</td>
</tr>
</table>
</body>
</html>
The html source of the output is as follows:
<html>
<head>
<title>Results</title>
</head>
<body>
<h1>ABC's results</h1>
<table border = 1>
<tr>
<td>Mathematics</td>
<td>100</td>
<td>100</td>
</tr>
<tr>
<td>chemistry</td>
<td>100</td>
<td>100</td>
</tr>
<tr>
<td>Physics</td>
<td>100</td>
<td>100</td>
</tr>
<tr>
<td>Total</td>
<td>0</td>
</tr>
</table>
</body>
</html>
Can someone please help me understand how to solve this?

The problem is that your total defined inside the loop is not the same total defined (and accessed) outside of loop. This is what local scopes do.
You can overcome this by using a hack like this (adapted from this answer).
<html>
<head>
<title>Results</title>
</head>
<body>
<h1>{{result["Name"]}}'s results</h1>
{% set total = [0] %}
<table border = 1>
{% for key, val in result.iteritems() %}
{% if key != 'Name' %}
{% set _ = total.append(total.pop() + val|int) %}
<tr>
<td>{{ key }}</td>
<td>{{ val }}</td>
<td>{{ total[0] }}</td>
</tr>
{% endif %}
{% endfor %}
<tr>
<td>Total</td>
<td>{{ total[0] }}</td>
</tr>
</table>
</body>
</html>
But I'm really not sure that it is a good idea to do such things in a template. The main idea of templates is to separate the logic (like counting the totals) and the representation, and this is a violation of this principle.

When you change variable value inside a loop does not effect outside of the loop except a dict:
{% set total = {'value': 0} %}
...
{% if total.update({"value": c|int + total.value|int }) %} {% endif %}
...
{{total.value}}

Related

Not able to send checkbox data from all pagination in datatable from template to view in django

I have a datatable in my django template in which there is a checkbox next to every row to send the row data to a view function to make some mass updations in django model. But problem is if the multiple rows are on the same page in pagination then i can send the data accurately BUT if i select row 2 from page 1 and row 5 from page 3 only the row value from page 3 will be sent to the view function.!
TEMPLATE.HTML
{% block jquery %}
<script type="text/javascript" class="init">
$(document).ready( function ($) {
var $submit = $("#updiv").hide(),
$cbs = $('input[name="updelegate"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
$('#myTable').DataTable({
dom: 'lBfrtip',
"pageLength": 1,
"language": {
"emptyTable": "No Delegates Available",
"sSearch": "Search Delegates: ",
"info": " Showing _START_-_END_ out of Total _TOTAL_ Delegates",
}
});
});
</script>
{% endblock %}
<form id="myForm" action="{% url 'mass-delegates' %}" method="POST">
{% csrf_token %}
<table id="myTable" class="table table-striped table-bordered" style="width:100%">
<thead class="thead-dark">
<tr>
<th></th>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Phone</th>
<th scope="col">Company</th>
<th scope="col">Designation</th>
<th scope="col">Address</th>
<th scope="col">City</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{% for del in delegates %}
<tr>
<td>
<label class="container">
<input type="checkbox" id="updelegate" name="updelegate"
value="{{ del.id }}">
<span class="checkmark"></span>
</label>
</td>
<td>{{ del.id }}</td>
<td>{{ del.first_name }} {{ del.last_name }}</td>
<td>{{ del.email }}</td>
<td>{{ del.phone }}</td>
<td>{{ del.company }}</td>
<td>{{ del.designation }}</td>
<td>{{ del.address }}</td>
<td>{{ del.city }} ({{ del.pincode }})</td>
<td>
View
</td>
<td>
Edit
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div id="updiv">
<select name="eventid">
{% for ev in events %}
<option value="{{ ev.id }}">{{ ev.name }}</option>
{% endfor %}
</select>
<input type="submit" onclick="return confirm('Confirm Adding to Event?');" class="upbtn"
name="update" value="Add to Event"/>
</div>
</form>
VIEW.PY
def mass_delegates(request):
if request.method == 'POST':
toupdate = request.POST.getlist('updelegate')
eventid = request.POST.get('eventid')
array_length = len(toupdate)
for i in range(array_length):
if not EventDelegate.objects.filter(event_id=eventid, delegate_id=toupdate[i]).exists():
EventDelegate.objects.create(event_id=eventid, delegate_id=toupdate[i])
return event_det(request, eventid)
Instead of using the checkboxes, you can directly use the select attribute in the Datatables api. Check Select Rows in Datatables
Moreover, Since you want to select multiple rows at once, you might consider checking Multi Select rows in Datatables out
You can add the id in the 0th column, then
dataTable = $(.selector).Datatable()
dataTable.columns([0]).visible(false);
You can hide the column like that and then when you send your request, you still have your id

How can I add a Bar Chart to my Django based Database?

Dear community members,
I really hope that you will help me to add a Bar Graph to my Django project.
1. I have a Database with around 1000 items.
2. I need to be able visualise a 3 month sales for each item when needed.
Not sure what is a correct approach.
here is my models.py:
from django.db import models
from math import *
from decimal import *
class Itemslist(models.Model):
item_n = models.CharField(max_length=200)
sales_this_month = models.DecimalField(blank=True, null=True, max_digits=19,
decimal_places=0)
saleslm = models.DecimalField(blank=True, null=True, max_digits=19, decimal_places=0)
sales2m = models.DecimalField(blank=True, null=True, max_digits=19, decimal_places=0)
sales3m = models.DecimalField(blank=True, null=True, max_digits=19, decimal_places=0)
def __str__(self):
return self.item_n
here is my views.py file, that as an experiment I have created, using the last solution provided:
def charts(request):
charts = Itemslist.objects \
.values('saleslm') \
.annotate(lm=Count('saleslm')) \
.annotate(m2=Count('sales2m')) \
.annotate(3m3=Count('sales3m')) \
.order_by('saleslm')
return render(request, 'charts.html', {'charts': charts})
As you can see, this is not a solution I need, I was just trying to come up with at least something , and eaven that has shown me the graph with the same values.
here is my hmtl code:
{% extends 'base.html' %}
{% block js %}
{% if user.is_authenticated %}
{% load loads_extra %}
{% load static %}
<br>
<p>Logged in user: {{ user.username }}</p>
<br>
<html>
<head>
<meta charset="utf-8">
<title>Django Highcharts Example</title>
</head>
<body>
<div id="container"></div>
{
<script src="https://code.highcharts.com/highcharts.src.js"></script>
<script>
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Sales previous 3 months'
},
xAxis: {
categories: ['sales']
},
series: [{
name: '3mBack',
data: [ {% for entry in charts %}{{ entry.m3 }}{% endfor %} ]
}, {
name: '2mBack',
data: [ {% for entry in charts %}{{ entry.m2 }}{% endfor %} ]
}, {
name: 'Lmonth',
data: [ {% for entry in charts %}{{ entry.lm }}{% endfor %} ]
}, ]
});
</script>
</body>
</html>
{% endif %}
{% endblock %}
<!-- charting tutorial to follow : https://simpleisbetterthancomplex.com/tutorial/2018/04/03/how-to-integrate-highcharts-js-with-django.html -->
I have to create a request button for charts and then chart has to be generated with a right parameters.
Have looked at this question:
Displaying multiple bar graph in django
Also have searched through this solution
https://code.djangoproject.com/wiki/Charts
And looked at this article
https://simpleisbetterthancomplex.com/tutorial/2018/04/03/how-to-integrate-highcharts-js-with-django.html
The last article was the clearest one, and you can see, that I have just copy pasted the solution from there, with small changes.
here is a script that I have placed in my base.html file:
<script src="https://code.highcharts.com/highcharts.src.js"></script>
and that's the chart that I have finally got displayed:
But still can’t find how to deal with it in my situation.
All this solutions, as far as I can see, are showing how to implement charting to one array, or to sum or self generated array. But I want to be able to chose, when to show a graph and for which Item.
the button is placed on this html file:
{% extends 'base.html' %}
{% block js %}
{% if user.is_authenticated %}
{% load loads_extra %}
{% load static %}
<br>
<p>Logged in user: {{ user.username }}</p>
<br>
<body>
<table id="example" class="table table-striped table-bordered dt-responsive nowrap" style="width:100%">
<thead>
<tr>
<th>SUP:</th>
<th>Item N.:</th>
<th>SKU</th>
<th>Description</th>
<th>3mBack</th>
<th>2mBack</th>
<th>Lmonth</th>
<th>CMonth</th>
<th>Nmonth</th>
<th>N2Month</th>
<th>N3month</th>
<th></th>
</tr>
</thead>
<tbody>
{% for records in sorted %}
<tr>
<td>{{ records.sup }}</td>
<td>{{ records.item_n }}</td>
<td>{{ records.sku }}</td>
<td>{{ records.description }}</td>
<td>{{ records.sales3m }}</td>
<td>{{ records.sales2m }}</td>
<td>{{ records.saleslm }}</td>
<td>{{ records.sales_this_month }}</td>
<td>{{ records.m1predicted }}</td>
<td>{{ records.m2predicted }}</td>
<td>{{ records.m3predicted }}</td>
<td>
Edit
</td>
</tr>
{% endfor %}
</tbody>
</table>
<script>
$(document).ready(function() {
var table = $('#example').DataTable( {
fixedColumns: true,
lengthChange: true,
buttons: [ 'copy', 'excel', 'csv', 'pdf', 'colvis' ]
} );
table.buttons().container()
.appendTo( '#example_wrapper .col-md-6:eq(0)' );
} );
</script>
</body>
</html>
{% endif %}
<div></div>
{% endblock js %}
This is my first question in this community, so if something is not clear, please help me to correct it in a right way.
waiting for any helpful answers!!!
Good News community.
I have been offered a very good solution, and now my question is completely sorted.
At least for my needs, this is a perfect solution.
instead of highcharts, I have been offered to use d3js.org, which is absolutely fine for me.
The logic behind a code is that you request data from the values displayed, hopefully it will be clear, when you will go through the code with comments.
as it's a django project, here's the heading of my html file:
{% extends 'base.html' %}
{% block js %}
{% if user.is_authenticated %}
{% load loads_extra %}
{% load static %}
<br>
<p>Logged in user: {{ user.username }}</p>
<br>
here is a part of my html code that displays table/value:
<table id="example" class="table table-striped table-bordered dt-responsive nowrap" style="width:100%">
<thead>
<tr>
<th>SUP:</th>
<th>Item N.:</th>
<th>SKU</th>
<th>Description</th>
<th>6mBack</th>
<th>5mBack</th>
<th>4mBack</th>
<th>3mBack</th>
<th>2mBack</th>
<th>Lmonth</th>
<th>CMonth</th>
<th>Nmonth</th>
<th>N2Month</th>
<th>N3month</th>
<th>AVGrowth</th>
<th></th>
<!-- This is header for new button to draw the Bar Charts -->
<th></th>
</tr>
</thead>
<tbody>
{% for records in sorted %}
<tr>
<td>{{ records.sup }}</td>
<td>{{ records.item_n }}</td>
<td>{{ records.sku }}</td>
<td>{{ records.description }}</td>
<td>{{ records.sales6m }}</td>
<td>{{ records.sales5m }}</td>
<td>{{ records.sales4m }}</td>
<td>{{ records.sales3m }}</td>
<td>{{ records.sales2m }}</td>
<td>{{ records.saleslm }}</td>
<td>{{ records.sales_this_month }}</td>
<td>{{ records.m1predicted }}</td>
<td>{{ records.m2predicted }}</td>
<td>{{ records.m3predicted }}</td>
<td>{{ records.avgrowths }}</td>
<td>
Edit
</td>
<!-- Add new button for drawing Bar Charts -->
<td>
<button class="btn btn-secondary" onclick="draw_chart(this)" data-toggle="modal" data-target="#myModal">Chart</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
please read comments to understand what is what.
and here is the rest of html, that is generating a chart on a topup window,by pressing a button in front of an array that has to be visualised:
<!-- Modal which Bar Chart will be placed -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog" style="max-width: 900px !important">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<!-- <svg> element which will contains the Bar Chart -->
<svg width="1000" height="500"></svg>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Insert D3.js Library -->
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
$(document).ready(function() {
var table = $('#example').DataTable( {
fixedColumns: true,
lengthChange: true,
buttons: [ 'copy', 'excel', 'csv', 'pdf', 'colvis' ]
} );
table.buttons().container()
.appendTo( '#example_wrapper .col-md-6:eq(0)' );
} );
// Main functions for Drawing Bar chart using D3.js
function draw_chart(item){
// `item` is the current clicked button element
// `row_ele` is the parent <tr> element of the current clicked button element
row_ele = item.closest('tr');
// Get the value from the <td> element using nth-child()
val_6mBack = row_ele.querySelector("td:nth-child(5)");
val_5mBack = row_ele.querySelector("td:nth-child(6)");
val_4mBack = row_ele.querySelector("td:nth-child(7)");
val_3mBack = row_ele.querySelector("td:nth-child(8)");
val_2mBack = row_ele.querySelector("td:nth-child(9)");
val_Lmonth = row_ele.querySelector("td:nth-child(10)");
val_CMonth = row_ele.querySelector("td:nth-child(11)");
val_Nmonth = row_ele.querySelector("td:nth-child(12)");
val_N2Month = row_ele.querySelector("td:nth-child(13)");
val_N3month = row_ele.querySelector("td:nth-child(14)");
// `data` is variable which store the data for Bar Charts
data = []
// Pushing data as key/value type objects into the `data` variable
data.push({'label':'6mBack', 'value': val_6mBack.innerHTML})
data.push({'label':'5mBack', 'value': val_5mBack.innerHTML})
data.push({'label':'4mBack', 'value': val_4mBack.innerHTML})
data.push({'label':'3mBack', 'value': val_3mBack.innerHTML})
data.push({'label':'2mBack', 'value': val_2mBack.innerHTML})
data.push({'label':'Lmonth', 'value': val_Lmonth.innerHTML})
data.push({'label':'CMonth', 'value': val_CMonth.innerHTML})
data.push({'label':'Nmonth', 'value': val_Nmonth.innerHTML})
data.push({'label':'N2Month', 'value': val_N2Month.innerHTML})
data.push({'label':'N3month', 'value': val_N3month.innerHTML})
// Set <svg> element's width and height
var svg = d3.select("svg"),
margin = 200,
width = svg.attr("width") - margin,
height = svg.attr("height") - margin
// Remove the old contents of the <svg> element
svg.selectAll('*').remove()
// Initialize X-axis and Y-axis for Bar Chart
var xScale = d3.scaleBand().range([0, width]).padding(0.4),
yScale = d3.scaleLinear().range([height, 0]);
// Set all group which is placed in the <svg>element
// transform to (50,100) on <svg> area , margint in svg has been changed to 300 and instead 50/100, changed to 100/300, but then back.
var g = svg.append("g")
.attr("transform", "translate(" + 50 + "," + 100 + ")");
xScale.domain(data.map(function(d) { return d.label; }));
// If all values of data will be zero, we will fix the range of the Y-axis
if(d3.max(data, function(d) { return d.value; }) == 0){
yScale.domain([0, 10]);
}else{
// If all is not zero, we will set Y-axis from 0 to maximum value.
yScale.domain([0, d3.max(data, function(d) { return Number(d.value); })]);
}
// Set X- axis
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xScale));
// Set Y-axis using ticket
g.append("g")
.call(d3.axisLeft(yScale).tickFormat(function(d){
return d;
}).ticks(10));
console.log(data)
// Draw Bar Chart using <rect> element by data which is stored in the `data` variable
g.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return xScale(d.label); })
.attr("y", function(d) { return yScale(d.value); })
.attr("width", xScale.bandwidth())
.attr("height", function(d) { return height - yScale(d.value); })
.style('fill','#899da6');
}
</script>
</body>
{% endif %}
{% endblock js %}
so finally here is how my html looks like live:
and here is a graph, that I get by pressing chart button:
in order to help community, please ask questions, and please add/correct if there is a better way.
Thank you very much for your help and attention!!!
views.py
You have an error on annotate(3m3 its cannot start with 3 here. You also have same function name and variable name def charts and charts inside. Python might be smart enough to figure it out but try to avoid doing this. I am also against naming variables saleslm and sales2m be explicit here.
def charts(request):
return render(request, 'charts.html')
def charts_ajax(request):
charts_data = Itemslist.objects \
.values('saleslm') \
.annotate(lm=Count('saleslm')) \
.annotate(m2=Count('sales2m')) \
.annotate(m3=Count('sales3m')) \
.order_by('saleslm')
return JsonResponse({'charts': list(charts_data)})
url.py
path('charts/', views.charts, name='charts_home'),
path('charts_ajax/', views.charts_ajax, name='render_charts_ajax')
html
You have multiple issues in your html file.
</html>
{% endif %}
<div></div>
{% endblock js %}
You have div after the html has ended. You should not have anything after html ends.
Few other organizational issues here. I usually would have a block content and then block js while you have everything inside block js. I would clean those. Now that you added datables also. You can add buttons as mentioned here. https://datatables.net/extensions/buttons/examples/initialisation/custom.html
but if i were you i would try to make it work with simple table and move on to datables.
<html>
<head>
<meta charset="utf-8">
<title>Django Highcharts Example</title>
</head>
<body>
<div id="container">
</div>
<button id="render_chart" type="button">Render Chart</button>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
<script>
$(document).ready(function(){
$('#render_chart').on('click', function(e){
$.ajax({
url: "{% url 'render_charts_ajax'%}",
type: "GET",
dataType: "json",
success: function (data) {
console.log(data.charts[0].saleslm)
Highcharts.chart('container',{
chart:{
type:'bar'
},
title:{
text:"Sales Last Month"
},
series:[{
name:"Sales LM",
data:[parseInt(data.charts[0].saleslm)]
}]
})
}
})
})
});
</script>
</body>
</html>
Your json might need some processing before the chart comes out right.

jinja2.exceptions.UndefinedError: object has no attribute

I am trying to create an Inventory Management System in which i can create/add stock through a form(WTForms) and have it displayed in a table on a separate page. Currently, i am stuck on the stated error. I have looked everywhere for an answer to no avail. I am supposed to add stock through 'createGPU.html' and be directed to 'retrieveGPU.html'
Clicking the submit button in createGPU results in jinja2.exceptions.UndefinedError: 'GPUs.GPUs object' has no attribute 'GPUName'
Main Program
from flask import Flask, render_template, request, redirect, url_for
from Forms import CreateGPUForm
import shelve, GPUs
#app.route("/createGPU", methods=['GET', 'POST'])
def createGPU():
createGPUForm = CreateGPUForm(request.form)
if request.method == 'POST' and createGPUForm.validate():
gpuDict = {}
db = shelve.open('storage.db', 'c')
try:
gpuDict = db['GPU']
except:
print('Error in retrieving GPUs from storage.db.')
gpu = GPUs.GPUs(createGPUForm.GPUName.data, createGPUForm.GPUUnitPrice.data, createGPUForm.GPUStock.data,createGPUForm.GPUSales.data)
gpuDict[gpu.get_GPUNo()] = gpu
db['GPU'] = gpuDict
db.close()
return redirect(url_for('retrieveGPU'))
return render_template('createGPU.html', form=createGPUForm)
if __name__ == '__main__':
app.run()
#app.route('/retrieveGPU')
def retrieveGPU():
gpuDict = {}
db = shelve.open('storage.db', 'r')
gpuDict = db['GPU']
db.close()
gpuList = []
for key in gpuDict:
gpu = gpuDict.get(key)
gpuList.append(gpu)
return render_template('retrieveGPU.html',gpuList=gpuList, count=len(gpuList))
createGPU
{% extends "base.html" %}
{% block title %}GPU-Assist - Add Graphics Card{% endblock %}
{% block content %}
{% from "includes/_formhelper.html" import render_field %}
<h1 class="display-4">Add Graphics Card</h1>
<form method="POST" action="">
<div class="form-group">
{{ render_field(form.GPUName, class="form-control") }}
</div>
<div class="form-group">
{{ render_field(form.GPUStock, class="form-control") }}
</div>
<div class="form-group">
{{ render_field(form.GPUUnitPrice, class="form-control") }}
</div>
<div class="form-group">
{{ render_field(form.GPUSales, class="form-control") }}
</div>
<input type="submit" value="Submit" class="btn btn-primary"/>
</form>
{% endblock %}
retrieveGPU
{% extends "base.html" %}
{% block title %}GPU-Assist - View GPU-Cart{% endblock %}
{% block content %}
<h1 class="display-4">View GPU</h1>
<div>
{% if count == 0 %}
<p>No GPU in recorded in inventory.</p>
{% elif count == 1 %}
<p>There is 1 GPU recorded in the inventory.</p>
{% else %}
<p>There are {{ count }} GPUs recorded in the inventory.</p>
{% endif %}
</div> <!--End of display number of users div-->
<div>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Stock</th>
<th>Unit Price</th>
<th>Sales</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{% for gpu in gpuList %}
<tr>
<td>{{ gpu.GPUName() }}</td>
<td>{{ gpu.GPUStock() }}</td>
<td>{{ gpu.GPUUnitPrice() }}</td>
<td>{{ gpu.GPUSales() }}</td>
<td>Update</td>
<td>
<form action="" method="POST">
<input type="submit" value="Delete" class="btn btn-danger">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
GPUs.py
class GPUs:
countID = 0
def __init__(self,GPUName,GPUStock,GPUUnitPrice,GPUSales):
GPUs.countID += 1
self.__GPUName = GPUName
self.__GPUStock = GPUStock
self.__GPUUnitPrice = GPUUnitPrice
self.__GPUSales = GPUSales
self.__GPUNo=GPUs.countID
'''
One obvious limitation it has is that every time you restart the web application, the countID resets to 0.
Once the countID resets, the next newly created Users’s userID will start from 1 again and overwrite any User
that previously had __userID = 1. (Must figure out an alternative)
'''
#Getter or Accessor
def get_GPUNo(self):
return self.__GPUNo
def get_GPUName(self):
return self.__GPUName
def get_GPUStock(self):
return self.__GPUStock
def get_GPUUnitPrice(self):
return self.__GPUUnitPrice
def get_GPUSales(self):
return self.__GPUSales
#Settor or Mutator
def set_GPUNo(self, GPUNo):
self.__GPUNo = GPUNo
def set_GPUName(self, GPUName):
self.__GPUName = GPUName
def set_GPUStock(self, GPUStock):
self.__GPUStock = GPUStock
def set_GPUUnitPrice(self, GPUUnitPrice):
self.__GPUUnitPrice = GPUUnitPrice
def set_GPUSales(self, GPUSales):
self.__GPUSales = GPUSales
When Jinja2 processes
<td>{{ gpu.GPUName() }}</td>
it expects that gpu will have a callable member function named GPUName. The way you've coded things up, get_GPUName is what you want instead.
The Pythonic way were be to drop the getters and setters entirely, removed the double-underscore prefixes, and have the template go directly for the named instance variable.
<td>{{ gpu.GPUName }}</td>

Flask use marked up db query return as argument?

I hope this is possible.
Is there a way to pass back a returned element from a db query as an argument to a url_for?
It is being marked up by jinja template, but it is not a form element.
#app.route('/matcher/', methods=['GET', 'POST'])
def show_entries():
#global account_id
global load_file_id
if request.method == 'GET':
option = str(request.args.get('button'))
load_file_id = int(request.args.get('a'))
if option == 'All':
sql = """SELECT *
FROM TABLE WHERE LOAD_FILE_ID = :load_file_id"""
c = g.db.cursor()
c.execute(sql, load_file_id=load_file_id)
rows = c.fetchall()
for row in rows:
entries = [dict(title=row[0], text=row[1], text1=row[2], text2=row[3], text3=row[4], text4=row[5], text5=row[6], text6=row[7])]
media = row[8]
account_id = int(row[0])
c.execute("""UPDATE TABLE SET STATUS = 'PENDING' WHERE ACCOUNT_ID = :account_id""", account_id=account_id)
g.db.commit()
outs = mediapod(account_id)
return render_template('show_entries.html', entries=entries, media=media, outs=outs, src=src)
c.close()
elif:
############DOESN'T MATTER#############
and then
{% extends "layout.html" %}
{% block body %}
{% if session.logged_in %}
{% for entry in entries %}
<div class=entry>
<form action="{{ url_for('next') }}" method=get
class=validate>
<h2 name=id>{{ entry.title }}</h2>
<div class=subentry>
<div class=titles>
INFO:<br>
INFO:<br>
INFO:<br>
INFO:<br>
INFO:<br>
INFO:<br>
INFO:<br></div>
<div class=elements>
${{ entry.text|string }}<br>
{{ entry.text1|string }}<br>
{{entry.text2|string }}<br>
{{ entry.text3|string }}<br>
{{ entry.text4|string }}<br>
{{ entry.text5|string }}<br>
{{ entry.text6|string }}<br></div>
<div class=mediatable>
<table>
<tr>
<th>Type</th>
<th>Date</th>
<th>Status</th>
<th>Doc ID</th>
<th>Scan Date</th>
</tr>
{% for put in outs %}
<tr>
<td>{{ put.media_type|safe }}</td>
<td>{{ put.statement_date|safe }}</td>
<td>{{ put.media_status|safe }}</td>
<td>{{ put.doc_id|safe }}</td>
<td>{{ put.scan_date|safe }}</td>
</tr>
{% endfor %}
</table>
</div>
<div class=buttons>
<input type=radio name=box value=match>Match
<input type=radio name=box value=nomatch>No Match
<input type=radio name=box value=fup>Follow-Up
<input type=radio name=box value=nomedia>No Media
<input type=submit class=next name=submit value=Next>
</div>
</div>
</form>
</div>
{% else %}
<em>stuff</em>
{% endfor %}
{% endif %}
{% endblock %}
and then I have a route after that that needs to take the account_id from show_entries()
#Next Button
#app.route('/next', methods=['GET'])
def next():
status = request.args.get('box')
c = g.db.cursor()
c.execute("""UPDATE TABLE
SET STATUS = :status
WHERE ACCOUNT_ID = :account_id""",
{"status" : str(status),
"account_id" : account_id
})
g.db.commit()
return redirect(url_for('nextnext'))
Take a peak back at the url_for docs:
It accepts the name of the function as first argument and a number of keyword arguments, each corresponding to the variable part of the URL rule.
url_for can be used in your Python source:
from flask import url_for
url_for('index')
and in your templates:
If you want your next method to receive a value as part of the URL, then you can change the method definition to
#app.route('/next/<int:account_id>', methods=['GET'])
def next(account_id):
# ...
then you can pass the variable through the url_for call, either from the Python source or from your templates:
url_for('next', account_id=account_id)
If you need your show_entries view to have that value in the template, then pass the value with the render_template call:
return render_template('show_entries.html', entries=entries, media=media, outs=outs, src=src, account_id=account_id)

How to get data from a form to jinja2

I am trying to get a value inputted through a form and then back into my jinja template. Which I know doesn't make sense so I guess I am asking how do I go about doing what I want?. Here is what I have:
Python
#app.route('/test', methods=['GET', 'POST'] )
def test():
posts = db.posts
facultyId = request.form.get("facultyId","");
print "facultyId: ",facultyId
return render_template('form.html',posts=posts,Id=facultyId)
form.html
<form method='post'>
<table width="80%" border="5" align="center" bgcolor="white">
<tbody>
<tr>
<th colspan= "4">
Faculty Identification Number:
<input type="text" id="facultyId" name="facultyId" value=""/>
</th>
</tr>
<tr>
<th colspan= "4">
Number Of Evaluations:
{% if posts.find({"Applicants.appId" : Id},{'Applicants.Evaluators':{'$exists': True }}).count() == 0 %}
{{posts.find({"Applicants.appId" : Id},{'Applicants.Evaluators':{'$exists': True }}).count() }}
{% else %}
{% for post in posts.find({"Applicants.appId" : Id}, { "Applicants.$.Evaluators" : 1 }) %}
{{post["Applicants"][0]["Evaluators"]|length}}
{% endfor %}
{% endif %}
</th>
</tr>
<th colspan= "4"><button type="submit" >Submit</button></th>
</tbody>
</table>
</form>
I want to be able to submit a facultyId though a form and have it go into my jinja and run my mongodb find query. It works if I hard code the value in so if I did Id=100 in my python it works but if I do it though the forums it doesn't and the facultyId value is getting inputted because it does prints out.
Try to set action controller as follows
<form method='post' action='/test'>
I think the problem is that you do not parse facultyId as an integer. It works if you hardcode 100, because it is an integer, but what you assign out of request.form is a string "100".
After
facultyId = request.form.get("facultyId","")
add
facultyId = int(facultyId) if facultyId else None
Try to put it in braces. Like this:
<form method='post'>
<table width="80%" border="5" align="center" bgcolor="white">
<tbody>
<tr>
<th colspan= "4">
Faculty Identification Number:
<input type="text" id="facultyId" name="facultyId" value=""/>
</th>
</tr>
<tr>
<th colspan= "4">
Number Of Evaluations:
{% if posts.find({"Applicants.appId" : {{Id}}},{'Applicants.Evaluators':{'$exists': True }}).count() == 0 %}
{{posts.find({"Applicants.appId" : {{Id}}},{'Applicants.Evaluators':{'$exists': True }}).count() }}
{% else %}
{% for post in posts.find({"Applicants.appId" : {{Id}}}, { "Applicants.$.Evaluators" : 1 }) %}
{{post["Applicants"][0]["Evaluators"]|length}}
{% endfor %}
{% endif %}
</th>
</tr>
<th colspan= "4"><button type="submit" >Submit</button></th>
</tbody>
</table>
</form>
I would also suggest to put your posts.find logic into your route function, then pass it's results to your form in the posts variable.

Categories

Resources