首页 > 解决方案 > 如何在 django 中获取按钮单击时的输入值

问题描述

我有一个 Django 模板如下

<table class="table">
    <thead>
        <tr>
            <th>#</th>
            <th>Master Title</th>
            <th>Retailer title</th>
            <th>To add</th>
        </tr>
    </thead>
    <tbody>
        {% if d %}
        {% for i in d %}
        <tr>
            <th scope="row">{{forloop.counter}}</th>
            <td>{{i.col1}}</td>
            <td>{{i.col2}}</td>
            <td>
                <input type="hidden" name='row_value' value="{{i.col1}}|{{i.col2}}">
                <a class='btn btn-success' href="{% url 'match' %}">Match</a>
                <a class='btn btn-outline-danger' href="{% url 'mismatch' %}">Not a Match</a>
            </td>
        </tr>
        {% endfor %}
        {% endif %}
    </tbody>
</table>

单击匹配按钮时,我想检索视图中隐藏输入的值。这是我的意见.py

def match(request):
    print(request.GET.get('row_value'))
    print('match')

但这返回无。

我希望 col1 和 col2 的值打印如下

col1|col2

我不确定我哪里出错了。

标签: pythondjangodjango-viewsdjango-templates

解决方案


您应该将 Django URL 参数与 GET 一起使用:

网址.py

   urlpatterns = [
       path('your-path/<int:first_param>/<int:second_param>', views.match),
   ]

来源:https ://docs.djangoproject.com/en/3.2/topics/http/urls/#example

视图.py

def match(request, first_param=None, second_param=None):
    # then do whatever you want with your params
    ...

来源:https ://docs.djangoproject.com/en/3.2/topics/http/urls/#specifying-defaults-for-view-arguments

模板:

        <td>
            <a class='btn btn-outline' href="your-path/{{i.col1}}/{{i.col2}}">Example</a>
        </td>

这是一个基本示例,因此请将其更改为您的用例。


推荐阅读