來自MySQL的數據正在顯示,其中不應包含額外字符。我正在使用Python 2.7和Django。使用Python檢索時的MySQL數據
我試圖尋找如何解決這個問題,但我不知道叫什麼的問題..
這是如何將數據顯示:(「皇家阿什」,)爲CharField或( 5L,)爲IntegerField(應該只顯示5)
我有一種感覺,這與JSON或類似的效果,但我不確定(我對此仍然很新)有沒有一種方法來解決這個?
View.py
def getCourses(request):
db = MySQLdb.connect(host="localhost", user="***", passwd="***", db="golf")
cur = db.cursor()
cur.execute("SELECT course_name FROM golfapp_golfcourses")
data = cur.fetchall()
"""cur.close()
connection.close()
sys.exit()"""
return render_to_response('DBTest.html', {'data':data})
course.html
{% include "base.html" %}
<html>
<body>
<select name="list_courses">
{% for data in data %}
<option>{{ data }} </option>
{% endfor %}
</select>
</body>
</html>
編輯 按上回答評論: Views.py
def GetAllCourses(request):
db = MySQLdb.connect(host="localhost", user="edwardb", passwd="edwards17", db="golfapp")
cur = db.cursor()
cur.execute("SELECT course_name, par_front_9, par_back_9, total_par FROM golfapp_golfcourses")
data1 = [course_name for (course_name,) in cur.fetchall()]
data2 = [par_front_9 for (par_front_9,) in cur.fetchall()]
data3 = [par_back_9 for (par_back_9,) in cur.fetchall()]
data4 = [total_par for (total_par,) in cur.fetchall()]
"""cur.close()
connection.close()
sys.exit()"""
return render_to_response('golfcourses.html', {'data1':data1}, {'data2':data2}, {'data3':data3}, {'data4':data4},)
模板:
{% extends "base.html" %}
{% block content %}
<table style="margin-left:15%" class="table table-bordered">
<tbody>
<th>
<td>Golf Course</td>
<td>Front 9</td>
<td>Back 9</td>
<td>Total Par</td>
</th>
<tr>
{% for data1 in data1 %}
<td>{{ data1 }} </td>
{% endfor %}
{% for data2 in data2 %}
<td>{{ data1 }} </td>
{% endfor %}
{% for data3 in data3 %}
<td>{{ data3 }} </td>
{% endfor %}
{% for data4 in data4 %}
<td>{{ data4 }} </td>
{% endfor %}
</tr>
</tbody
</table>
</div>
{% endblock %}
「L」只是表示它是一個整數,它不會顯示在屏幕上。 ()是結果的元組。 –
L實際上沿着括號和逗號顯示在html模板列表框中。 – edwards17