I am trying to write a simple flask application where I am using a Postgresql as database. I am trying to update the table row on button click but it is giving me following error
DataError: (psycopg2.DataError) invalid input syntax for integer: "125/" LINE 1: ...ATE tasks SET taskname='IamUpdated' WHERE tasks.uid = '125/' ^ [SQL: 'UPDATE tasks SET taskname=%(taskname)s WHERE tasks.uid = %(uid_1)s'] [parameters: {'taskname': 'IamUpdated', 'uid_1': u'125/'}]
I am not sure if it is adding "/" at the end as a glitch or it is supposed to be like that? or That is what causing an error.
Please Help.
Following is my Flask Python code
edituser = request.form.getlist('editId')
if edituser:
for e in edituser:
User.query.filter_by(uid=e).update(dict(taskname="IamUpdated"))
db.session.commit()
return render_template("index.html",User=User.query.all())
Following is my HTML code
<form action="" method="POST">
<div ng-controller="myctrl" >
<table>
<caption> Todo List</caption>
<thead>
<tr>
<td>
<input type="text" name="text">
<input type="submit" value="Add Task" >
</td><td>
Search :<input type="text">
</td>
</tr>
<tr>
<th>Task Id</th>
<th>Task</th>
</tr>
</thead>
<tbody>
{% for user in User %}
<tr>
<td> {{ user.uid }} </td>
<td >{{ user.taskname }}
<input type="image" class="deleteImg" src="static/img/trash_can.png" height="15px" width="18px" name="removeId" value={{user.uid}} />
<input type="image" src="static/img/editbtn.svg" height="15px" width="18px" name="editId" value={{user.uid}}/>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<script>
var app = angular.module("app", ['xeditable']);
app.controller('myctrl', function($scope) {
$scope.myname="Howdy";
});
app.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('//').endSymbol('//');
});
app.run(function(editableOptions) {
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});
</script>
</form>
</body>
Your problem seems to be this tag here:
<input type="image" src="static/img/editbtn.svg" height="15px" width="18px" name="editId" value={{user.uid}}/>
All values in html are strings. Therefore they must all be quoted.
value="{{user.uid}}"
Once you've done this, HTML will know exactly what you meant to include in the value, rather than guessing.
The reason this hasn't affected other fields is because this is the only time you didn't put a space between the value and the number.
The error was because I have "/>" at the end of the input tag. it was unnecessary. I have removed it and now it is working fine.
Related
This is what i tried till now but it doesn't work. How can i correct this code.
Please note that the for loop is created by using flask module in python
{% for row in items %}
<tr>
<td>{{row.0}}</td>
<td>{{row.1}}</td>
<td><input type="checkbox" value="{{row.0}}" name="items"></td>
<td> <input name="it.{{row.0}}"></td>
<tr>
{%endfor%}
I have a form with dynamically added rows that have the same name. I try to use getlist but I only get the first value.
Here is my HTML form code:
<html>
<div>
<form method=POST>
</div>
<table id="linkTable">
<tbody><tr class="tr_clone" id="addrow">
<td>First: </td>
<td><input class="from-field" id="from" type="text" name="first"></td>
<td>Last: </td>
<td><input class="to-field" id="to" type="text" name="last"></td>
<td>Email: </td>
<td><input class="port-field" id="ports" type="text" name="email"></td>
</tr>
</tbody></table>
<script>
$("#addbtn").click(function(){
$("#addrow").clone().find("input:text").val("").end().prependTo("#linkTable");
})
</script>
</form>
</html>
Here is my python code:
from flask import Flask, request, render_template
for arg in request.form:
print arg, request.form.getlist(arg)
Can anyone explain that even if I use getlist, I only get the first value?
Thanks in advance
It's convenient to use zip() every time you want to parse same name attribute in html. Have a look at this:
#app.route('/creation', methods=['GET', 'POST'])
def create():
try:
if request.method == 'POST':
for first, last, email in zip(request.form.getlist('first'),
request.form.getlist('last'),
request.form.getlist('email')):
print(first, last, email)
else:
return render_template('create.html')
except Exception as e:
print(str(e))
After looking for a long time, was able to answer my own question by looking on the web.
I had the following:
<html>
<!-- note how the form has been moved out of the div so that the navigator does not close the div -->
<form method=POST>
<table id="linkTable">
<tbody><tr class="tr_clone" id="addrow">
<td>First: </td>
<td><input class="from-field" id="from" type="text" name="first"></td>
<td>Last: </td>
<td><input class="to-field" id="to" type="text" name="last"></td>
<td>Email: </td>
<td><input class="port-field" id="ports" type="text" name="email"></td>
</tr>
</tbody></table>
<script>
$("#addbtn").click(function(){
$("#addrow").clone().find("input:text").val("").end().prependTo("#linkTable");
})
</script>
</form>
</html>
It turns out that closing a div will close a form tag so rows were being dynamically added outside the form. By moving the form directive outside of the div, I started getting multiple values when the form was submitted
I also eventually found a more detailed answer at Form Issue (closing itself early in table)
Python/Flask/Bootstrap noob here. I'm trying to build a web-app to control a speaker selector. I'm using bootstrap and Ti-Ta Toggles to beautify the app a bit, but basically it consists of 4-5 checkbox/toggles. Here's what my HTML looks like right now:
<form name="input" action="/" method="post">
<div class="row">
<div class="col-md-6">
<table class="table">
<tbody>
<tr>
<td>Living Room</td>
<td>
<div class="checkbox checkbox-slider-lg checkbox-slider--a checkbox-slider-info">
<label>
<input name="spkrs-00" type="checkbox" onclick="this.form.submit()" checked><span></span>
</label>
</div>
</td>
</tr>
<tr>
<td>Kitchen</td>
<td>
<div class="checkbox checkbox-slider-lg checkbox-slider--a checkbox-slider-info">
<label>
<input name="spkrs-01" type="checkbox" onclick="this.form.submit()"><span></span>
</label>
</div>
</td>
</tr>
<tr>
<td>Dining Room</td>
<td>
<div class="checkbox checkbox-slider-lg checkbox-slider--a checkbox-slider-info">
<label>
<input name="spkrs-02" type="checkbox" onclick="this.form.submit()"><span></span>
</label>
</div>
</td>
</tr>
<tr>
<td>Unconnected</td>
<td>
<div class="checkbox checkbox-slider-lg checkbox-slider--a checkbox-slider-info">
<label>
<input name="spkrs-03" type="checkbox" onclick="this.form.submit()" disabled><span></span>
</label>
</div>
</td>
</tr>
<tr>
<td>Protection</td>
<td>
<div class="checkbox checkbox-slider-lg checkbox-slider--a checkbox-slider-warning">
<label>
<input name="protection" type="checkbox" onclick="this.form.submit()"><span></span>
</label>
</div>
</td>
</tr>
</tbody>
</table>
</div>
So, what I'm trying to figure out is how to handle the POST data from the checkbox inputs in my Python/Flask app. I was trying to do a simple test which looks like the following:
from flask import Flask, request, render_template
import time
app = Flask(__name__)
#app.route('/', methods=['POST','GET'])
def change():
if request.method == 'POST':
spkr_00_state = request.args['spkrs-00']
spkr_01_state = request.args['spkrs-01']
spkr_02_state = request.args['spkrs-02']
protection_state = request.args['protection']
speaker_states = [spkrs_00_state, spkrs_01_state, spkrs_02_state, protection_state]
return render_template('index.html', speaker_states=speakers_states)
else:
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=80)
However, I get Bad Request messages, etc. So, I'm a bit lost on how this should work. Should I create separate forms for each toggle? Should I put "try" if statements around the request.args?
OK, just in case someone else stumbles upon this post later and is curious, I was able to figure out what my issues were. Mainly, my issue was that by default checkboxes will only POST when checked. Therefore if you do not have a particular box checked (in this case it was the toggle switches I was using in bootstrap Ti-Ta Toggles) then there will be no POST information when checked.
In Flask/Python, when you try to request the post data for a particular checkbox/toggle, and it doesn't exist, then you will get a bad request error. For example, the following will likely generate an error if the checkbox spkrs_02 after POST.
spkr_state[1] = request.form['spkrs_02']
The way to get around this is to use a hidden input tag after the input tag for the checkbox. This will return a value in post, even if the input tag isn't checked/toggled.
For example it would look like something like this (in your HTML file) if you were setting up a checkbox(toggle) using :
<input name="spkrs_02" type="checkbox" onclick="this.form.submit()"><span>Kitchen</span>
<input name="spkrs_02" type="hidden" value="off">
That last line will, as mentioned above, provide some feedback in post, when the "box" is not checked.
Also a side note that I used onclick="this.form.submit()" which was helpful in tacking action on a toggle/checkbox immediately when it is clicked. I'll be honest that I'm not sure if that is the proper way to handle this, but it worked well for me.
Anyway, good luck!
I have a piece of angular code within a bigger Python Django HTML page -
{% verbatim %}
<div ng-controller="FwCompController">
<tbody ng-repeat="fwComp in fwCompList">
<tr>
<td>
<div class="form-group" >
<select name="{{mycomp}}" class="compName">
<option value="{{fwComp.value}}" selected="true">{{fwComp.title}}</option>
<option value="none">None</option>
</select>
</div>
</td>
<td>
<div class="form-group">
<input class="form-control" type="text" name={{fwComp.pathName}} placeholder={{fwComp.pathPlaceHolder}}/>
</div>
</td>
</tr>
</tbody>
</div>
{% endverbatim %}
Angular -
var app = angular.module('boombox', []);
app.controller('FwCompController', function ($scope) {
this.fwCompList = [
{
name: "compName1",
value: "mba",
title: "UEFI",
pathName: "compPath1",
pathPlaceHolder: "/hsc_sw_dvt/rels/mba/7.10.70/evpxe.nic",
}];
$scope.mycomp = "compName1";
});
The table rows do not get printed in the resulting HTML page. Why ? Is it valid to assign angular vars as HTML attribute values ?
You should bind the fwCompList to $scope
$scope.fwCompList = [
{
name: "compName1",
value: "mba",
title: "UEFI",
pathName: "compPath1",
pathPlaceHolder: "/hsc_sw_dvt/rels/mba/7.10.70/evpxe.nic",
}];
In your legacy code, you bind fwCompList to this, which is your controller FwCompController but not $scope. If you don't want to change your controller, you should change your HTML to
<div ng-controller="FwCompController as fw">
<tbody ng-repeat="fwComp in fw.fwCompList">
This is my current Html i would like to grab the rootname and the currentplatform from my root table and create a new row on my log table using the root name.
<div id="container">
<div id = "left" >
{%for status in root|slice:":1" %}
<h1><center>Root List by {{status.rootgroup}} Rootgroup<center></h1>
{% endfor %}
<h3 id="time">current: </h3>
<table border = "2">
<tr>
<th><input type="checkbox" id="selectall"/> Check All</th>
<th>Rootname </th>
<td>Urls</td>
<th> custs </th>
<th> jvmms </th>
<th> x64 </th>
<th> currentplatform </th>
<th> currentjdk </th>
<th> currenttomcat </th>
<td><p>Date: <input type="text" id="datepicker" size="10" /></p></td>
<td><input type="text" value="12:00" size="5" /><td>
<select name="ampm">
<option value="am">AM</option>
<option value="pm">PM</option>
</select>
</tr>
{% for status in root %}
<tr >
<form name= "/display2/" method="POST">
<td align="center"><input type="checkbox" class="selectedId" onclick="resetSelectedAll(this);" id="row{{ forloop.counter }}" ></td>
<td name = "root" id="row{{forloop.counter}}rootname">{{ status.rootname }}</td>
<td name= "server" id="row{{forloop.counter}}urls">{{ status.urls }}</td>
<td id="row{{forloop.counter}}custs">{{ status.custs }}</td>
<td id="row{{forloop.counter}}jvmms"> {{ status.jvmms }}</td>
<td id="row{{forloop.counter}}x64">{{ status.x64 }}</td>
<td id="row{{forloop.counter}}currentplatform"> {{ status.currentplatform }}</td>
<td id="row{{forloop.counter}}currentjdk"> {{ status.currentjdk }}</td>
<td id="row{{forloop.counter}}currenttomcat">{{ status.currenttomcat }}</td>
</tr>
{% endfor %}
</table>
<select name="action">
<option value="Restart">Restart</option>
<option value="Full_Dump">Full_Dump</option>
<option value="Redeploy">Redeploy</option>
<option value="Thread">Thread</option>
</select>
<input type="submit" onclick="check()" value="submit"/>
This is my current view i would like to replace the stuff surrounded in asterix with text from my html which will then create a new row in a different table based on the information i choose. I tried using forms, but i do not want to input data i already have the data displayed just need to call it or connect the 2 going backwards.
def display2(request, value=None):
log = Logofsupport._meta.get_all_field_names()
rootFilter = Viewroot.objects.filter(rootstatus__gt=0, type =1, jvmms=1024, rootgroup = value).distinct()#Root List by RootGroup
if request.method == 'POST':
log = LogofsupportForm(request.POST)
# action = request.Get.get('action')
if log.is_valid:
new = LogofsupportForm**(servername="appBOWSERtest032", rootname="appBOWSERtest032",requesteddate='07/16/2013', action="restart", loginname="justin")**
new.save()
else:
log= LogofsupportForm()
return render_to_response('status/root_server.html', { 'root' : rootFilter, 'log': log },context_instance=RequestContext(request))
I don't fully understand what the objective of your process is, but I think the answer to your question is to create the string of HTML you want in your python code instead of using the template file.
In other words, take the tr with all the forloop.counters and recreate it in a string in a python function. Then load that string as a template variable, in effect pasting in each HTML row inside the template. Then inside your logging function, you can call the same python function that creates each row, effectively "importing" it.
It is possible to "get the HTML", but that would require some kind of asynchronous request via Javascript that sends the HTML you want as an HTTP request argument. There is a library called dajax which can automate the process of sending asynchronous javascript requests to Django, but for your purposes it would be much less difficult to simply refactor the way you are creating the HTML.