рендер значения в шаблон из json объекта python
У меня есть метод profileи шаблон profile.html.
В profile.html есть выпадающий список из мейлов пользователей. Когда я выбираю один из них, появляется модальное окно с этим мейлом, и я могу отправить ему сообщение. Я получаю этот мейл туда через AJAX.
Проблема в том, что born_date и phone_number этого пользователя, которые я получаю из базы данных, не отображаются в шаблоне, и я не вижу их в модальном окне. В чем может быть проблема?
def str_value_to_list(text: str):
*_, email_json = re.findall(r'[^ \',()]+', text)
return email_json
#метод profile страницы
@app.route('/profile', methods=['GET','POST'])
def profile():
if request.method == 'GET' and 'loggedin' in session:
cur = mysql.connection.cursor()
cur.execute("SELECT firstname, lastname, email FROM users.data WHERE description = 'doctor'")
account = cur.fetchall()
description = account
countries = ['USA','France','Italy','Spain','Australia','New Zealand']
return render_template(
'profile.html',
id = session['id'],
email = session['email'],
firstname = session['firstname'],
description = description,
countries = countries
)
#метод для получения даты и номера в модальном окне
@app.route('/api/get_data', methods=['POST'])
def get_data():
if request.method == 'POST':
print('Holy Shit!')
data = request.json
print(str_value_to_list(data['selectedItems'][0]))
cur = mysql.connection.cursor()
cur.execute("SELECT born_date, phone_number FROM users.data WHERE email = '%s'" % str_value_to_list(data['selectedItems'][0]))
account = cur.fetchone()
born = account[0]
num = account[1]
print(born)
print(num)
return jsonify({
'born': born,
'num': num,
})
#метод отправки сообещние на почту юзеру
@app.route('/api/send_msg', methods=['POST'])
def send_msg():
if request.method == 'POST':
docs = request.json('sel')
print(docs)
for doc in docs:
print(type(doc))
res = doc.split()
print(res[2].replace("'","")[:-1])
message = request.form['text']
# imgInp = request.form['imgInp']
file = request.files['file']
print(file)
# create message object instance
msg = MIMEMultipart()
#message = imgInp
password = "mypass19@20"
msg['From'] = "[email protected]"
msg['To'] = str(res[2].replace("'","")[:-1])
msg['Subject'] = "New Symptom"
# add in the message body
msg.attach(MIMEText(message, 'plain'))
#send pdf docs
file_to_send = MIMEApplication(file.stream.read())
file_to_send.add_header('Content-Disposition', 'attachment', filename=file.filename)
msg.attach(file_to_send)
#create server
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
# Login Credentials for sending the mail
server.login(msg['From'], password)
# send the message via the server.
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
success_msg = "All data have been sent to your doctor!"
print(success_msg)
return jsonify({
'result': "Сообщение отправлено успешно",
})
html
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog"
aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Information about user</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p class="form-control" id="mySelectedValue" style="margin-top: 10px;"></p>
<input type="text" name="text" class="form-control" placeholder="Add your message here"required="required">
<h2 class="white-text" style="font-size: 14px; color: #000;">born: </h2>
<h2 class="white-text" style="font-size: 14px; color: #000;">num: </h2>
<button class="btn btn-primary send">
Send
</button>
</div>
</div>
</div>
</div>
скрипт получения данных в модальное окно
<script>
function printValue(selectedItem) {
$('#mySelectedValue').html(selectedItem.value.replace(/[{()}]/g, '').replace(/['"]+/g, '').replace(/[{,}]/g, ''));
console.log(selectedItem.value);
}
function process(selectedItem) {
$('#exampleModalCenter').modal('show')
document.getElementById('#exampleModalCenter')
const data = JSON.stringify({
"selectedItems": $('#sel').val()
});
$.ajax({
url: "/api/get_data",
type: "POST",
contentType: "application/json",
data: data,
success: function (data) {
h2 = document.querySelectorAll('.white-text')
h2[0].innerText = `born: ${data.born}`
h2[1].innerText = `num: ${data.num}`
},
});
}
function optionClick(selectedItem) {
printValue(selectedItem);
}
</script>