I want to code a small message feed for my homepage. I want to send a text from a textarea to my Database
this is my html template:
{% extends 'layout.html'%}
{% block body%}
<form action="/feed" method="post">
<table>
<tr>
<td><textarea name="feedtext" id="feedtext" placeholder="Type message here!" rows="4" cols="53"></textarea></td>
</tr>
<tr>
<td><button style="width: 65%;" "submit"\>Send</button></td>
</tr>
</table>
</form>
{% endblock %}
now my problem is the python part. I try anything but I don't get the right code.
this is my python code now:
#app.route('/feed', methods=['POST'])
def feed():
try:
conn = mysql.connect()
cursor = conn.cursor()
feedtxt = request.form['feedtext']
cursor.execute('INSERT INTO nachrichten (Vorname, Nachname, Nachricht) VALUES(%);', (feedtxt))
finally:
cursor.close()
conn.close()
Welcome.
Can not make out "I try anything but I don't get the right code".
Anyway, out of the columns
(Vorname, Nachname, Nachricht)
it seems only the Nachricht gets the value of (feedtxt).
Try giving 3 items within VALUES
Related
I'm trying to make a simple login page using python flask and MySQL. The webpage itself is being made using html, bootstrap 4 and css. I followed a tutorial to make the login page but now I want to add a way to delete an account.
This is a profile page which is visible after you login(it shows your username, password and email). The database table(called accounts) has a primary key id. The part in /// is the code I'm trying to add for creating a delete button. Please help me fix my delete account button.
#app.route('/pythonlogin/profile', methods = ['GET'])
def profile():
# Check if user is loggedin
if 'loggedin' in session:
# We need all the account info for the user so we can display it on the profile page
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM accounts WHERE id = %s', (session['id'],))
account = cursor.fetchone()
# Show the profile page with account info
return render_template('profile.html', account=account)
# User is not loggedin redirect to login page
///if request.method == 'GET':
id = session['id']
mycursor = mysql.cursor()
sql = ('DELETE from accounts WHERE id = 4;')
# return redirect(url_for('logout)')
mycursor.execute(sql)
mysql.connection.commit()///
return redirect(url_for('login'))
The following is the html part called profile.html.
{% extends 'layout.html' %}
{% block title %}Profile{% endblock %}
{% block content %}
<h2>Profile Page</h2>
<div>
<p>Your account details are below:</p>
<table>
<tr>
<td>Username:</td>
<td>{{ account['username'] }}</td>
</tr>
<tr>
<td>Password:</td>
<td>{{ account['password'] }}</td>
</tr>
<tr>
<td>Email:</td>
<td>{{ account['email'] }}</td>
</tr>
<tr>
<form action="{{ url_for('logout') }}">
<td>
<button type="submit" class="btn btn-danger">Delete Account</button>
</td>
</form>
</tr>
</table>
</div>
{% endblock %}
In the provided code I can see some mistakes (logical)
If use logged in, code after return render_template('profile.html', account=account)
will not be executed
And another problem is that you are creating the URL to logout instead of the profile page <form action="{{ url_for('logout') }}">
And better to do the form with POST method.
I want to display the content of the database from .db file on web framework using flask module. However, only the row title is able to be displayed on the web framework. The content of the database from the .db file couldn't load out on the web framework. Anyone can help me with this? Thanks.
This is my code:
from flask import Flask, render_template
import sqlite3
app = Flask(__name__)
def connect_db(db):
con = sqlite3.connect(db)
return con.cursor()
#app.route('/')
def index():
db ='mcu_aurix_git.db'
cur = connect_db(db)
cur.execute("SELECT * FROM mcu_aurix")
data = cur.fetchall()
return render_template('flask.html', rows=data)
if __name__ == "__main__":
app.run(debug=True)
flask.html:
<table class="table table-hover">
<thead>
<tr>
<th>project</th>
<th>branch</th>
<th>id</th>
<th>number</th>
<th>subject</th>
<th>owner_name</th>
<th>owner_email</th>
<th>owner_username</th>
<th>url</th>
<th>commitMessage</th>
<th>createdOn</th>
<th>lastUpdated</th>
<th>open</th>
<th>status</th>
<th>current_date</th>
</tr>
</thead>
<tbody>
{% for row in rows %}
<tr>
<td>{{row.project_name}}</td>
<td>{{row.branch_id}}</td>
<td>{{row.id_id}}</td>
<td>{{row.num_number}}</td>
<td>{{row.subject_name}}</td>
<td>{{row.owner_name}}</td>
<td>{{row.owner_email}}</td>
<td>{{row.owner_username}}</td>
<td>{{row.url_name}}</td>
<td>{{row.commitMessage_name}}</td>
<td>{{row.num_createdOn}}</td>
<td>{{row.num_lastUpdated}}</td>
<td>{{row.num_open}}</td>
<td>{{row.status_name}}</td>
<td>{{row.current_date}}</td>
</tr>
{% endfor %}
</tbody>
</table>
Is there anything missing in my code? Hopefully anyone can help me on this. Thanks in advance!
You are not passing rows variable to the html page.
return render_template('flask.html', data=data)
You are only passing data variable.
If you want to use rows inside your html page, you need to use
return render_template('flask.html', rows=data)
Also one more thing,
{{row.project_name}}
You cannot get the value of project_name like this, you need to use index value (col. no. starting from 0). Like,
{{row[0]}}
Instead of manually creating <td> for each col value, you can just use the below tbody code.
<tbody>
{% for row in rows %}
<tr>
{% for col in row %}
<td> {{ col }} </td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
Hope it helps!
I have built a forum in pythonanywhere using python and html, in which users can post information that gets inserted into a sqlite database. At the bottom of each post is a delete button that will delete the post that it's under from the database and refresh the page. Right now the delete button only refreshes the page while the post remains. I am wondering how to edit the code so that the post which the form button is attached to is deleted and the page is refreshed.
HTML Code snippet
{% for post in forumposts %}
<tr>
<td>
<h1>{{post[1]}}</h1>
<h3>{{post[3]}}</h3>
<p>{{post[2]}}</p>
<p>{{post[6]}}</p>
<img src="{{post[7]}}" alt="Wrong image link.">
<p></p>
<form action="{{ url_for('delete_post') }}" method=POST class=delete-post>
<input type=hidden value="{{ postid }}"name=post_to_delete></input>
<input type=submit></input>
</form>
</td>
</tr>
{%endfor%}
</table>
Python Code snippet
#app.route('/delete', methods=['POST'])
def delete_post():
db = connect_db()
db.execute('DELETE FROM posts WHERE postid = ?', [request.form['post_to_delete']])
db.commit()
db.close()
return redirect(url_for('forum'))
Got the code working.
HTML
{% for post in forumposts %}
<tr>
<td>
<h1>{{post[1]}}</h1>
<h3>{{post[3]}}</h3>
<p>{{post[2]}}</p>
<p>{{post[6]}}</p>
<img src="{{post[7]}}" alt="Wrong image link.">
<p></p>
<form action="{{ url_for('delete_post') }}" method=POST class=delete-post>
<input type=hidden value={{post[0]}} name=post_to_delete></input>
<input type=submit value=POST></input>
</form>
</td>
</tr>
{%endfor%}
</table>
PYTHON
#app.route('/delete', methods=['POST'])
def delete_post():
if request.method == 'POST':
db = connect_db()
db.execute('DELETE FROM posts WHERE postid = ?', (request.form['post_to_delete'],))
db.commit()
db.close()
return redirect(url_for('forum'))
Hope this helps someone. :)
Hello Stackoverflow community,
I am new to FLASK however while the learning curve has been very steep, there is one item that I have not been able to get my head around.
I am using a very simple HTML seach form, into which users type the name of a city, this input gets passed to a Mysql query and returns output into a Table.
Everything works except that I can't get the variable to pass into Mysql... if I fix the query it works.
I tried to work with FLASK WTForms, POST and GET requets, but I don't know where I am going wrong.
The variable data that I am passing is not confidencial, so I have no concern if it shows up in the URL.
Here just the simple FORM (I guess not correct)
<form>
<div class="form-group">
<div class="col-sm-3">
<input type="text" placeholder="City Name" name="City_Name" action=/search class="form-control">
</div>
<div class="form-group">
<div class="col-sm-2">
<input type="submit" value="SEARCH" class="btn btn-primary btn-block">
</div>
</div>
</form>
Here the table output (working perfectly)
<table class="table table-striped">
<tr>
<th>PO_Number</th>
<th>Plant Name</th>
<th>GMID</th>
<th>Material</th>
<th>INCOTERM</th>
<th>Vendor</th>
<th>Vendor Count</th>
</tr>
{% for row in tabledata %}
<tr>
<td>{{ row['PO_Number'] }}</td>
<td>{{ row['PN'] }}</td>
<td>{{ row['GD'] }}</td>
<td>{{ row['MN'] }}</td>
<td>{{ row['INCO'] }}</td>
<td>{{ row['VNGS'] }}</td>
<td>{{ row['CVNGS'] }}</td>
</tr>
{% endfor %}
</table>
Here the Python code
from flask import Flask, render_template, request, url_for
from dbhelper_single_search import DBHelper
app = Flask(__name__)
DB = DBHelper()
#app.route('/table')
def table():
try:
tabledata = DB.table_inputs()
except Exception as e:
print(e)
tabledata = None
return render_template("table.html", tabledata=tabledata)
if __name__ == '__main__':
app.run(port=5000, debug=True)
Data Base Helper Mysql (the valye for PLN should change based on the input in the Form.
import pymysql
class DBHelper:
def table_inputs(self):
connection = self.connect()
PLN="**City_Name**"
try:
query = "SELECT Plant_Geo, Plant_Code, Plant_Name, GMID, Material_Name, GROUP_CONCAT(DISTINCT Vendor_Name_GS ORDER BY Vendor_Name_GS) as VNGS, sum(2014_USD), sum(2015_USD), sum(2016_USD) FROM invoice_report WHERE plant_code like '%s' GROUP BY GMID ORDER BY sum(2015_USD) DESC" %(PLN);
with connection.cursor(pymysql.cursors.DictCursor) as cursor:
cursor.execute(query)
return cursor.fetchall()
finally:
connection.close()
Thank you in advance for any help.
I think you need to set the action on the <form> element, rather than <input> and you want to direct it to the same Flask endpoint (I assume?):
<form method="GET" action>
<div class="form-group">
<div class="col-sm-3">
<input type="text" placeholder="City Name" name="City_Name" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<input type="submit" value="SEARCH" class="btn btn-primary btn-block">
</div>
</div>
</form>
Update your helper class a little to accept a city variable from your view function (you could tighten this up a bit more):
import pymysql
class DBHelper:
def table_inputs(self, city):
connection = self.connect()
PLN = "**%s**" % city
try:
query = "SELECT Plant_Geo, Plant_Code, Plant_Name, GMID, Material_Name, GROUP_CONCAT(DISTINCT Vendor_Name_GS ORDER BY Vendor_Name_GS) as VNGS, sum(2014_USD), sum(2015_USD), sum(2016_USD) FROM invoice_report WHERE plant_code like '%s' GROUP BY GMID ORDER BY sum(2015_USD) DESC";
with connection.cursor(pymysql.cursors.DictCursor) as cursor:
# actually better to pass parameters like this:
cursor.execute(query, (PLN,))
return cursor.fetchall()
except Exception as err:
# this may also help find errors generated above...
print(err)
finally:
connection.close()
Then, update your view function to test if city is submitted and submit it to your helper class:
#app.route('/table')
def table():
// the second argument is the default if "City_Name" is not submitted
city = request.args.get('City_Name', 'New York')
try:
tabledata = DB.table_inputs(city)
except Exception as e:
print(e)
tabledata = None
return render_template("table.html", tabledata=tabledata)
I'm new to coding and have to do this for a school assignment. I do not have very good knowledge of code but I have to create a to-do list webpage that uses a database (SQLite3) to store the to-dos and users. I have the to-do list page successfully showing the created to-dos but I want a button beside the to-dos pulled from the database (to-dos are in table format) that will delete the table row that it is next to. I am not using django or anything like that, so is there a way that this can be done without any python extensions?
Here's my python flask code for my to-do list page
#app.route('/todo', methods=['GET','POST'])
def todo():
error = None
if 'login' in session:
user = session['userid']
db = connect_db()
cursor = db.execute("SELECT * from todolist where userid=?",(user,))
userdetails = cursor.fetchall()
db.commit()
db.close()
if request.method == 'POST':
userid = session['userid']
db = connect_db()
cursor = db.execute("DELETE FROM todolist where userid=?",(userid,))
userdetails = cursor.fetchall()
db.commit()
db.close()
return render_template('todo.html',userdetails=userdetails)
else:
flash('Please login')
return redirect(url_for('.login'))
else:
flash('Please login')
return redirect(url_for('.login'))
And here's my to-do html code for the table section, the rest contains bootstrap links and whatnot:
<h1>Your to-do list!</h1>
<p>{{message}}</p>
<body>
<table border=1 style="width:100%">
{% for row in userdetails %}
<tr id='todorow'>
<td>
<form action="">
<input type="checkbox" name="complete" value="Complete">
</form>
</td>
<td>
{{row[2]}}
</td>
<td>
{{row[3]}}
</td>
<td><form action="/todo" method='POST'>
<input type=submit name="delete" value="Delete"></input>
</form></td>
<td><form action="/todoedit">
<input type="submit" value="Edit item"
onclick="window.location='/todoedit';" /></input>
</form></td>
</tr>
{%endfor%}
If anyone could please explain to me how I can use a html submit button to delete the to-do on the same row as the button, deleting the to-do data from the todolist database table, or what I am doing wrong in my code, and please, if you don't mind, explaining how your code works to do this.