I'm tring to do my first web app using python 3.4 and Bottle.
I'm tring do create a dropdown list using data from one table colled "Documenti" (using sqlite)
The table used has only two columns: ID_D (id) and Documents (name of document).
My need is that when a value is choosed, and the botton "search" cliked, Bottle opens a new page, using the ID_D value from the first table and printing info from a second table (colled "Master") thet has also a column colled ID_D.
I'm tring to do this using these codes:
first page with dropdwon list (using first table)
#route('/doc')
def Document():
conn = sqlite3.connect('db.db')
c = conn.cursor()
result = c.execute("SELECT ID_D FROM documenti;").fetchall()
c.close()
output = template('doc', rows=result)
return output
Second page, opened using the ID_D from the previous page to print info from the second table
#route('/docx', method='GET')
def docx():
if request.GET.get('search','').strip():
id = request.GET.get('docx', '').strip()
conn = sqlite3.connect('db.db')
c = conn.cursor()
c.execute("SELECT * FROM master WHERE ID_D LIKE ?;" (id))
result = c.fetchall()
c.close()
output = template('doc3', rows=result)
return output
Here there is my html code used...
in the page with the dropdown list:
<form action="/docx" method="GET">
<select name="docx"><option selected="selected" value="">Seleziona</option>
%for row in rows:
<option value="{{row}}">{{row}}</option>
%end
</select>
<input type="submit" name="search" value="search">
In the second page (where i wont to see info from the second table using as filter ID_D:
<table border="1">
%for row in rows:
<tr>
%for col in row:
<td>{{col}}</td>
%end
</tr>
%end
</table>
My codes doesn't work...the second page is blank...
Thanks to all for your help!
Mauro
EDIT:
for everyone...this is my working code:
#route('/docx', method='GET')
def docx():
id = request.GET.get('docx', '').strip()
conn = sqlite3.connect('db.db')
c = conn.cursor()
result = c.execute("SELECT * FROM master WHERE ID_D LIKE (?)", (id,)).fetchall()
c.close()
output = template('doc3', rows=result)
return output
Thanks to all guys!
I believe that if request.GET.get('search','').strip(): is evaluating to False and your view is thus returning None, which is the default behavior in Python. This makes sense as a submit button does not include itself in the query string. I would try this:
#route('/docx', method='GET')
def docx():
id = request.GET.get('docx', '').strip()
conn = sqlite3.connect('db.db')
c = conn.cursor()
c.execute("SELECT * FROM master WHERE ID_D LIKE ?;" (id))
result = c.fetchall()
c.close()
output = template('doc3', rows=result)
return output
If it still doesn't work, I would try right-clicking on the page (when opened in a browser) and selecting View Source and you should see a blank page, if you see something like this:
<table border="1">
</table>
then the SQL query is wrong.
Related
i am using this code for retrieving value from sql column to textbox. and i am using textmode="date" at input time to save DATE in database.And using a gridview link i want to redirect the row data to another page for edit and update.But the DATE value is not coming to TEXTBOX.
Date_of_st.Text = ds.Tables[0].Rows[0][5].ToString();
Also tried these snippets:
1 Convert.ToDateTime(dt.Rows[0]["Employee_DOB"]).ToString("dd-MM-yyyy");
2 ((DateTime)ds.Tables[0].Rows[0]["Coat_CUSTM_Date"]).ToString("yyyy-MM-dd");
3 suDateTime = DateTime.ParseExact(conv, "MM-dd-yyyy", null);
Suppose the row and col are correct, try this:
var date = ds.Tables[0].Rows[0][5].ToString();
var dateRif = new DateTime();
if (DateTime.TryParse(date, out dateRif))
{
//Do what you want
}
Hi I have created a simple tree view using SQL query but now I also wanted to download it which I am unable to because I don't have any one2many field so I don't know how to loop else of that
Right now it's giving me a report of one line each page but I wanted all lines together and I want them in pdf, not in xls. I have tried storing query fetched data in an array but that doesn't work for me and I don't know even if we can do that or not
class PostgresReport(models.Model):
'''
This module is responsible for all of the requisition related operations.
'''
_name = 'purchase.comp'
_auto = False
#all fields
name = fields.Char(string = 'Purchase Order')
origin = fields.Char(string ='Purchase Agreement')
date_order = fields.Datetime('Order Date', index=True, copy=False)
state = fields.Selection([
('draft', 'RFQ'),
('sent', 'RFQ Sent'),
('to approve', 'To Approve'),
('purchase', 'Purchase Order'),
('done', 'Locked'),
('cancel', 'Cancelled')
], string='Status', readonly=True, index=True, copy=False, default='draft', track_visibility='onchange')
product_id = fields.Char(string='Product')
product_qty = fields.Float(string='Quantity')
price_unit = fields.Float(string='Unit Price')
price_subtotal = fields.Monetary(string='Subtotal', store=True)
vendor = fields.Char(string='Vendor')
currency_id = fields.Char('Currency')
'''
This function is responsible for fetching data from 3 different tables and displaying it
'''
#api.model_cr
def init(self, _logger=None):
""" Event Question main report """
query = []
tools.drop_view_if_exists(self._cr, 'purchase_comp')
view = self._cr.execute(""" CREATE VIEW purchase_comp AS (
SELECT
b.id as id,
a.name as "name",
a.origin as "origin",
a.date_order as "date_order",
a.state as "state",
b.name as "product_id",
b.product_qty as "product_qty",
b.price_unit as "price_unit",
b.price_subtotal as "price_subtotal",
c.display_name as "vendor",
d.name as "currency_id"
FROM public.purchase_order as a
inner join
public.purchase_order_line as b
on a.id = b.order_id
inner join
public.res_partner as c
on a.partner_id = c.id
inner join
public.res_currency as d
on d.id = b.currency_id
WHERE a.origin != ''
order by a.name
)""")
I am not posting web code as it is simple and obvious. kindly just tell me from the .py code which field can I use for looping in XML and if I can't use any what should I do in this case. Thanks in advance
Create a button y any wizard and return a report action with the records you want to print attached as datas, so, like this you can use a foreach in the report:
#api.multi
def print_lines(self):
self.ensure_one()
records = self.env['purchase.comp'].search([]) # take all records to print
active_ids = [] # we have the active records in 'records' variable just to print one report,
# so we do not really need any active id, add some id if you get any error
datas = {
'ids': active_ids,
'model': 'purchase.comp',
'form': self.read()[0],
'records_to_print': records
}
report_name = 'module_name.report_name'
report_obj = self.env['ir.actions.report'].search([
('report_name', '=', report_name),
('report_type', '=', report_type)
], limit=1).report_action(
[], data=datas)
return report_obj
I confess I did not try my solution, but I have taken some ideas from the hr module. It may work, try it and tell me if it worked
Apologies about the language, I'm maintaining a legacy system which is all in ASP Classic.
I have a html page which has content generated from my SQL Server via ASP
<form method="POST">
<div class="container">
<table id="table" class="table">
<thead class="thead-dark">
<tr>
<th scope="col" data-field="article">Article</th>
<th scope="col" data-field="item">QTY/th>
I then generated the content with a while loop from my dB which displays the content correctly :
<%
While not grs.eof
%>
<tr>
<!--SQL query from ASP-classic-->
<th><%=grs.fields("Article")%></th>
<input type="number" class="form-control" id="Quant" placeholder="<%=grs.fields("QTY")%>" name="qty"></th>
<%
grs.movenext
wend
%>
</tr>
</table>
</form>
Now, above my table I have a button
<button type="submit" value="Submit" class="btn btn-primary mb-2" name="B1">Confirm</button>
When my end user clicks submit, I want all the values to be updated into my SQL server, now as this is within a for loop I wasn't sure where the Update query would go.. I have this so far
<%
If request.form("B1")="Submit" Then
If QTY = "" Then
QTY = 0
Else
QTY = request.form("QTY")
'Update SQL'
gsSQL2 = "UPDATE dB SET quant ='" & QTY & "' WHERE ID = '" & request.querystring("ID") & "' And Article = '" & grs.fields("Article") &"'"
gobjConn.Execute(gsSQL2)
(please note my code is indented properly in my IDE)
Now, when I click submit within the While loop I get the ID number seperated by a comma, so I know it's updating but I'm really unsure as to what I'm doing wrong..?
any help would be much appreciated.
if any further information is needed let me know.
Expected output is to display some Article Codes codes on a website and take a response from the user, then write that output to my SQL dB where the Article = Article and ID = ID.
main query to generated content (this doesn't match my sample data but I'll post incase the mistake is in the query itself)
gsSQL = "SELECT ID, Article, [Item Name] as name, [Stock Quantity] as qty, Built, Boxed, Actual from dB where Store ='" & request.querystring("store") & "' order by [Category], name "
Set grs = gobjConn.Execute(gsSQL)
With hopes that I understand you correctly, you have id, quant, and article already in database and want to update the quant related to the ID. In that case:
In the loop that creates the form give each number input a name with the ID in the name (or if you just have one field just have the ID as the name). In your case:
<input type="number" name="qty<%=rs("ID")%>">
On the action page you then loop through all the fields and update accordingly, either you do a replace on the name to get the ID, or if you only use the ID as fieldname it works without replace:
For Each Item In Request.Form
fieldName = Item 'This is the ID (with above field name: qtyID where ID is the ID from the DB.
fieldValue = Request.Form(Item) 'This is the Quantity of that Article ID
articleid=replace(fieldName,"qty","")
sql="update table set qty=" + fieldValue + " where id=" + articleid
Next
That way you will go through all the fields in the form. I am also unsure if you need both ID and Article in where clause? Can one ID have many Articles or vice versa?
I need to have a sqldatasource with the following sql in it.
if #filter = 'departments'
begin
SELECT ISNULL(DocTitle,'') as Name, DocNumber as id, DocUrl+DocName AS link,LastModBy,LastModDate, IsLink
FROM cmc.CMC_Docs d
INNER JOIN CMC.CMC_Doc_Locations as l on l.FamilyID = d.FamilyID
INNER JOIN CMC.CMC_DocFamilies df on df.FamilyID = d.FamilyId
WHERE IsEnabled=1
AND ISNULL(DocName,'') <> ''
AND d.FamilyID IN #dep
ORDER by DocTitle
end
where #dep is something like (2,3)
However when I try to test the query I get an error saying incorrect syntax near #dep.
Any ideas how I need to write this inside of the datasource in order for it to work?
Thanks,
do you need to put this in ()?
ex: select * from product where productid in (1,2,3) works
ex: select * from product where productid in 1,2,3 - does not work
i have a datatable which contains "InvalidCodes".
Before uploading the data to database(data is still in datatable), i want to perform linq on the datatable to remove Invalid entries and move them in another datatable
datatable allEntries ( entries yet to be uploaded in database)
datatable InvalidCodes(single column datatable - retrieved from database)
datatable invalidEntries
right now "allEnties" contains valid entries and invalid entries. the linq query on "allEntries" should move the nonexistend code entries to invalidEntries datatable.
plz help me perform this.
below is the query i formed but its not valid
string query = "select [CityCode] from [StateCity] ";
DataTable citylist = getDataTableFromSelect(query);
var result = from myrow in inputDt.AsEnumerable()
where !myrow.Field<string>("CityCode").Contains(from myrow2 in citylist.AsEnumerable() select myrow2.Field<string>("CityCode") )
select myrow;
I'd make a HashSet for the invalid city codes - this will allow the code to quickly/efficiently identify which of the codes are in the invalid set.
e.g. something like:
var invalidCityCodes = from myrow2 in citylist.AsEnumerable()
select myrow2.Field<string>("CityCode");
var invalidCityCodeHashSet = new HashSet<string>(invalideCityCodes);
var result = from myrow in inputDt.AsEnumerable()
where !invalidCityCodeHashSet.Contains(myrow.Field<string>("CityCode"))
select myrow;
You can also take both the results in 2 Different Lists and then you can
use
List1 = List1.RemoveAll(Item=>List2.Contains(Item))
This works fine with me and will work for you also.