Django write in database when form is submit - python

i want to use html form to be able to send back information to my view.py, the goal is to get the data, use it as arguments in a call to a stored procedure.
def mouvementCreation(request):
idMI = 0
especes = TbEspece.objects.order_by('id')
#Get Mouvement informations
#Connection to 'erp-site' DB
cursor = connections['erp-site'].cursor()
try:
#Get Produits list from Espece
query = "{CALL SP_webGET_PRODUIT_FROM_ESPECE(%s,%s,%s,%s,%s)}"
arguments = (2016, 'C', 0, 10, 'A',)
cursor.execute(query, arguments)
produits = dictfetchall(cursor)
#Get Transporters list
cursor.execute("{CALL SP_webGET_TRANSPORT}")
transporters = dictfetchall(cursor)
#Get Livreur list
cursor.execute("{CALL SP_webGET_LIVREUR}")
livreurs = dictfetchall(cursor)
finally:
cursor.close()
cursor = connections['site'].cursor()
try:
#Get Circuit list
cursor.execute("{CALL SP_webGET_CIRCUIT_FOR_MVT}")
circuits = dictfetchall(cursor)
#Get Source list
cursor.execute("{CALL SP_webGET_SOURCE_FOR_MVT}")
mvtsources = dictfetchall(cursor)
#Get Dest list
cursor.execute("{CALL SP_webGET_DEST_FOR_MVT}")
destinations = dictfetchall(cursor)
#Get PontBascule list
cursor.execute("{CALL SP_webGET_PBASCULE}")
pontBascules = dictfetchall(cursor)
finally:
cursor.close()
reg_normes = TbRegauxnormes.objects.all()
ordreexecs = TbOrdreexecution.objects.all()
form = mouvementForm(request.POST or None)
if form.is_valid():
pont = form.cleaned_data['pont']
dateheure = form.cleaned_data['dateheure']
poid = form.cleaned_data['poid']
dsd = form.cleaned_data['dsd']
typepesee = form.cleaned_data['typepesee']
#Connection to 'erp-site' DB
cursor = connections['pontbascule'].cursor()
try:
#Get Produits list from Espece
query = "{CALL SP_ADD_MANUAL_PESEE(%s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s)}"
arguments = (pont, '11', dateheure, poid, dsd,typepesee, '','','','','','','','','','','','','','','','')
cursor.execute(query, arguments)
finally:
cursor.close()
return render(request, 'mouvementCreation.html', {'form': form, 'especes' : especes, 'produits' : produits, 'transporters' : transporters, 'livreurs' : livreurs, 'circuits' : circuits, 'mvtsources' : mvtsources, 'destinations' : destinations, 'pontBascules' : pontBascules} )
The stored procedure is supposed to create a new entry.
What i want to do, but i'm not sure if possible would be :
Fill form => retrieve data in view => call stored procedure with the retrieved data => get the ID of the new entry so the user can be redirected to a another view that take the id in url parameters.
Would this be possible to do ?
Edit : I managed to get the post request working aswell as my stored procedure, my problem is now for the last part, redirecting the user on the right page after submiting the form.
the current page is /gestion_mouvement/mouvementCreation and i want the user to be redirected on /gestion_mouvement/mouvementDetails/{{ID}}
Problem is it seem that the query is too slow, because by the time i submit the form the user gets redirected to /gestion_mouvement/mouvementDetails/
and not recieving the ID.

What about creating a new cursor to fetch your last id created?
cursor.execute("SELECT max(id) from MANUAL_PESEE")
return {rec[0] for rec in cursor}

I've had the same issue recenly. Here is what I did.
Query concerned object model just after insert (after form.save()) and get the max(id) generated
form.save()
#mynewid = Msg.objects.all().order_by("-id")[0].id
mynewid = Msg.objects.latest('id').id
return redirect('/msg/{0}/edit/'.format(mynewid))

Related

trying to get current user using session flask, but variable returns an empty list

Im creating an event manager web app.. and right now I'm trying to query the events that the current user is in.
#classmethod
def getevent(cls, id):
cursor = mysql.connection.cursor()
sql = f"SELECT name, description FROM event Where p_id = {id} Order by id"
cursor.execute(sql)
result = cursor.fetchall()
return result
this is the function that gets the event name and description where Participant ID (p_id) is equal to the current user (session['userID']
#routes.route("/listofevents", methods = ['POST', 'GET'])
def Levents():
id = session['userID']
events = models.Event.getevent(id)
print(id)
print(events)
return render_template("index_ListofEvents.html", events = events)
the route. This works fine but nothing shows up in the webpage.. when i try to print the the events it returns an empty list []
Can anybody help me please. What am I missing?
EDIT:
when I run the query in phpmyadmin it works but I need to replace {id} in string format e.g. '2020-6969' but when I print session it just returns int
2020-6969

Python/Flask/SQLite App validating against a different table before creating record in another table but not rendering final HTML

My app is/isn't writing to the DB under the right conditions so that's all working fine. It's checking one table for PSIReg number and if it exists in pharmaValidate table and if it exists, writing the record into pharmacies table.
The last little step where it renders a page in the case of the reg number being invalid is returning:
TypeError: The view function for 'PharmaReg' did not return a valid response. The function either returned None or ended without a return statement.
The desired behaviour is that it renders PharmaRegFail.html in the case of invalid PSIReg number and the record not writing to the DB (the latter part is already happening)
#app.route('/PharmaReg', methods=["POST", "GET"])
def PharmaReg():
msg = "msg"
with sqlite3.connect("mypharmaSQLite3.db") as con:
if request.method == "POST":
try:
PSIReg = request.form["PSIReg"]
PharmaName = request.form["PharmaName"]
PharmaPhone = request.form["PharmaPhone"]
PharmaAddress = request.form["PharmaAddress"]
PharmaEmail = request.form["PharmaEmail"]
realPharma = con.execute('select * from pharmaValidate where PSIReg = ?', [PSIReg])
validPharma = realPharma.fetchone()
if validPharma:
with sqlite3.connect("mypharmaSQLite3.db") as con:
cur = con.cursor()
cur.execute("INSERT into pharmacies (PSIReg, PharmaName, PharmaPhone, PharmaAddress, PharmaEmail) values (?,?,?, ?, ?)", (PSIReg, PharmaName, PharmaPhone, PharmaAddress, PharmaEmail))
con.commit()
msg = "Pharmacy successfully registered"
con.close()
return render_template("successRegPharm.html", msg=msg)
except:
return render_template("PharmaRegFail.html")
#app.route('/pharmaRegFail.html')
def pharmaRegFail():
return render_template("pharmaRegFail.html")

How to use flask variable in calling SELECT query in MariaDB

What is the correct syntax for calling a SELECT query in MariaDB from a Registration Form.
Specifically, in the WHERE clause. I've been looking all over the net to debug this and it does not seem to work (semantically).
Here is the code in my python flask.
#app.route('/check_email', methods = ['POST', 'GET'])
def chck_Email():
if request.method == 'POST':
visEmail = request.form['email']
conn = mariadb.connect(**config)
print(f"WE ARE CONNECTED ORAYT")
# create a connection cursor
cur = conn.cursor()
# execute an SQL statement
try:
print(visEmail)
#sql = " INSERT INTO visitor (Visitor_ID, Visitor_Name) VALUES( NULL, '{}')".format(Visitor_ID, Visitor_Name)
current_Email= cur.execute("SELECT user_Email FROM user_account WHERE user_Email = ?",(visEmail,))
print(current_Email)
if current_Email != None:
print('Email Invalid: Email already exists!')
form = Registration_Form()
exists = {
"email_exists": True
}
return render_template(exists,'register.html', form = form )
""The visEmail is the variable that is supposed to be holding the email address given by the user upon clicking submit, the program then checks in the database if the given email address already exists in the DB.
I printed the data in the visEmail variable to see the string(Which is fine), but the execution in the database returns me with "None" (It should not be returning a None since I already have the given email address on the DB). It is supposed to return the error "Email Already exists"
THank you very much
You're not fetching the row of results. cur.execute() doesn't return anything, you have to call cur.fetchone() to get the results, and assign that to current_Email.
try:
print(visEmail)
#sql = " INSERT INTO visitor (Visitor_ID, Visitor_Name) VALUES( NULL, '{}')".format(Visitor_ID, Visitor_Name)
cur.execute("SELECT user_Email FROM user_account WHERE user_Email = ?",(visEmail,))
current_Email = cur.fetchone()
print(current_Email)
if current_Email != None:
print('Email Invalid: Email already exists!')
form = Registration_Form()
exists = {
"email_exists": True
}
return render_template(exists,'register.html', form = form )

Flask WTForms new inputs are not overwriting prepopulated data upon submission

I have a flask WTForms form which I am prepopulating with fields from my DB. From there I want to enable the user to update the values of any fields if they choose and re-insert this into the database. The specific issue I'm having with the below sample code is that when I submit the form, there is no data seen in the form.data dictionary (printed on line 18). Those fields are empty even though I've typed information into them. My guess is that form.field1.data is still holding the value it did from the database (line 11), and not taking in the data which the user has typed in.
However I cannot figure out how to otherwise structure the form in order to handle this. code below, thanks
#hp_blueprint.route('/formpage',methods=['GET','POST'])
def build_form():
#setup the QualitativeForm with values from the DB as placeholders
with sfsql_engine.connect() as conn:
df = pd.read_sql("SELECT * FROM MY_TABLE WHERE 1=1",conn)
if len(df) == 0:
form = QualitativeForm()
else:
form = QualitativeForm()
form.field1.data = df['field1'].values[0]
form.field2.data = df['field2'].values[0]
form.field3.data = df['field3'].values[0]
#write to DB upon submission
if form.is_submitted() and form.validate():
#WHEN I PRINT THIS OUT, IT DOES NOT HOUSE ANY OF THE DATA THAT I JUST TYPED IN
print(form.data)
print("the form update worked properly")
field1 = form.field1.data
field2 = form.field2.data
field3 = form.field3.data
with sfsql_engine.connect() as conn:
conn.execute("INSERT INTO MY_TABLE(field1,field2,field3) VALUES (%s,%s,%s)",
field1,field2,field3)
print("inserts ran correctly")
return redirect('/formpage')
For me it looks like you are overwriting the values of the form in your else statement - the code will be executed both in the "get" and in the "post" case. Therefore, I would change the order of both blocks and rewrite it like this:
#hp_blueprint.route('/formpage',methods=['GET','POST'])
def build_form():
form = QualitativeForm()
#write to DB upon submission
if form.is_submitted() and form.validate():
#WHEN I PRINT THIS OUT, IT DOES NOT HOUSE ANY OF THE DATA THAT I JUST TYPED IN
print(form.data)
print("the form update worked properly")
field1 = form.field1.data
field2 = form.field2.data
field3 = form.field3.data
with sfsql_engine.connect() as conn:
conn.execute("INSERT INTO MY_TABLE(field1,field2,field3) VALUES (%s,%s,%s)",
field1,field2,field3)
print("inserts ran correctly")
return redirect('/formpage')
#setup the QualitativeForm with values from the DB as placeholders
with sfsql_engine.connect() as conn:
df = pd.read_sql("SELECT * FROM MY_TABLE WHERE 1=1",conn)
if len(df) > 0:
form.field1.data = df['field1'].values[0]
form.field2.data = df['field2'].values[0]
form.field3.data = df['field3'].values[0]
# return the template with the form or continue with the code...

PostgreSQL + Python: Check if record exist using variables

referring to this documentation
Iam trying to compare JSON data
jsonResponse = json.loads(dataString) { 'login' : 'login' }
username_input = jsonResponse["login"] login
to database record using this call:
cur.execute("SELECT * FROM users WHERE username = '?'" % username_input)
than iam calling for specific one catched and use another variable
username_database = cur.fetchone()
to compare for executing loop
if username_input == username_database:
username_password = jsonResponse["password"]
cherrypy.log(str(username_password))
conn.commit()
But I am receiving None value from database username_database = None

Categories