You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django视图如何获取点击的cl_itemid并调用PostgreSQL更新函数

解决Django视图获取cl_itemid并执行PostgreSQL函数的问题

1. 修正URL路由配置

你的模板通过{% url 'update' data.cl_itemid %}生成带参数的链接,因此需要在urls.py中定义接收cl_itemid参数的路由:

path('update/<str:cl_itemid>/', views.update, name='update'),

这里用<str:cl_itemid>匹配字符串类型的cl_itemid(如OSA2022-2023这类格式)。

2. 修改views.py中的update函数

当前模板的<a>标签发起的是GET请求,但你的原代码只处理POST请求,这里提供两种实现方案:

方案一:直接处理GET请求(快速实现)

若只是简单更新操作,可直接在GET请求中处理(敏感操作建议用POST,避免误触发):

from django.db import connection

def update(request, cl_itemid):
    # 直接接收URL传递的cl_itemid参数
    with connection.cursor() as cursor:
        # 使用参数化查询避免SQL注入,禁止直接拼接字符串!
        cursor.execute("SELECT resolve_clearance_item(%s)", [cl_itemid])
    return render(request, 'clearance/index.html')

方案二:改用POST请求(更安全)

为避免误触发更新,建议将链接改为表单提交:

<table style="width:100%">
    <tr>
        <th>cl_itemid</th>
        <th colspan="2">Actions:</th>
    </tr>
    {% for data in data %}
    <tr>
        <td>{{data.cl_itemid}}</td>
        <td>
            <form method="POST" action="{% url 'update' data.cl_itemid %}">
                {% csrf_token %}
                <button type="submit">Update</button>
            </form>
        </td>
    </tr>
    {% endfor %}
</table>

对应修改views.py:

from django.db import connection

def update(request, cl_itemid):
    if request.method == "POST":
        with connection.cursor() as cursor:
            cursor.execute("SELECT resolve_clearance_item(%s)", [cl_itemid])
        return render(request, 'clearance/index.html')
    # GET请求可返回提示或直接跳转
    return render(request, 'clearance/index.html')

3. 关键注意事项

  • 禁止直接拼接SQL字符串:原代码的字符串拼接方式存在严重SQL注入风险,必须使用参数化查询(用%s作为占位符,参数放入列表传入)。
  • URL参数类型匹配:因cl_itemid是包含字母和横杠的字符串,所以用<str:cl_itemid>;若为数字则改用<int:cl_itemid>。

内容的提问来源于stack exchange,提问作者Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 21:05:21