【发布时间】:2021-06-14 21:09:09
【问题描述】:
我正在尝试使用 Django 将 PostgreSQL 表提取到 HTML 中,当我在 PostgreSQL 的查询工具中执行空间查询时,我得到了完美的结果,但是当我尝试从 Django 执行相同的脚本时,得到所有行数据的。感谢您提前提供帮助。
SQL query which is working perfectly
SELECT *
FROM jhk_schls as point,jhk_urban as polygon
WHERE ST_Within(point.geom, polygon.geom)
Django 脚本
def search(request):
if request.method == "POST":
first_layer = request.POST.get('first_layer')
spati_func = request.POST.get('spa_func')
second_layer = request.POST.get('secon_layer')
within_fun = 'select * from' + " " + str(first_layer) + " " + 'as point,' + str(second_layer) + " " + 'as polygon' + " " + 'WHERE' + " " + str(spati_func)+'(point.geom, polygon.geom)'
cursor = connection.cursor()
cursor.execute(within_fun)
data = cursor.fetchall()
return render(request, 'geoit/search.html',{ 'data':data})
return render(request,'geoit/search.html')
HTML
<span>Select Layer</span>
<select name="first_layer">
<option value="-1" disabled selected >Please select</option>
Layer<li><option value="jhk_schls">jhk_schls</option></li>
</select>
</br>
<span>Spatial Functions</span>
<select name="spa_func">
<option value="-1" disabled selected >Please select</option>
Layer<li><option value="ST_Within">ST_Within</option></li>
</select>
</br>
<span>Select Layer</span>
<select name="secon_layer">
<option value="-1" disabled selected >Please select</option>
Layer<li><option value="jhk_urban">jhk_urban</option></li>
</select>
<input type="submit" value="submit">
</p>
</div>
</form>
<button type="submit" value="submit"><i class="fa fa-search"></i>
</button>
</form>
<p></p>
<center>
<table>
{% for item in data %}
<tr>
<td>{{ item.0 }}</td>
<td>{{ item.2 }}</td>
</tr>
{% endfor %}
</table>
</center>
```
【问题讨论】:
-
两件非常重要的事情:在 Django 中,您不使用 SQL,而是使用 ORM,如果在其他情况下必须使用 SQL,则永远不要使用字符串连接来构造它。这将导致 SQL 注入漏洞。你拿了Djangotutorials吗?
-
能否提供解决问题的教程?否则,提供任何类似的项目。我是 Django 的中级。
标签: python html django postgresql postgis