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

Django无法识别点击的是哪个image类型input按钮,求解决方案

解决Django中图片按钮点击判断问题

问题根源:HTML的type="image"按钮提交表单时,不会将value作为POST参数传递,而是会发送name.x和name.y两个坐标参数,所以你原来通过response.POST.get("accept")无法检测到点击事件。

下面提供两种可行解决方案:

方案一:给图片按钮添加name属性,通过坐标参数判断

修改前端代码,为每个图片按钮添加name属性:

<form method="POST">
    {% csrf_token %}
    <input type="image" name="accept" value="accept" class="v" src="{% static 'main/assets/icons/v.png' %}">
    <input type="image" name="decline" value="decline" class="x" src="{% static 'main/assets/icons/x.png' %}">
</form>

后端通过检测对应坐标参数是否存在来判断点击:

if request.method == "POST":
    if "accept.x" in request.POST:
        return render(request, "main/calender-page.html", {})
    elif "decline.x" in request.POST:
        return render(request, "main/account-page.html", {})

方案二:改用submit按钮+CSS替换为图片(推荐)

这种方式更符合表单提交的常规逻辑,后端处理更直观:

前端代码

<form method="POST">
    {% csrf_token %}
    <input type="submit" name="action" value="accept" class="v">
    <input type="submit" name="action" value="decline" class="x">
</form>

对应CSS(替换为你的图片尺寸)

.v {
    border: none;
    background: url("{% static 'main/assets/icons/v.png' %}") no-repeat center;
    width: 30px; /* 替换为你的图片宽度 */
    height: 30px; /* 替换为你的图片高度 */
    cursor: pointer;
    text-indent: -9999px; /* 隐藏按钮文字 */
    overflow: hidden;
}

.x {
    border: none;
    background: url("{% static 'main/assets/icons/x.png' %}") no-repeat center;
    width: 30px; /* 替换为你的图片宽度 */
    height: 30px; /* 替换为你的图片高度 */
    cursor: pointer;
    text-indent: -9999px; /* 隐藏按钮文字 */
    overflow: hidden;
}

后端代码

if request.method == "POST":
    action = request.POST.get("action")
    if action == "accept":
        return render(request, "main/calender-page.html", {})
    elif action == "decline":
        return render(request, "main/account-page.html", {})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:03:41