【问题标题】:How to access html button values in django views如何在 django 视图中访问 html 按钮值
【发布时间】:2020-09-30 15:27:50
【问题描述】:

我正在开发一个 django 网络应用程序。该应用程序在表单中有几个按钮。这些按钮的作用类似于拨动开关。当用户提交表单时,我想访问 django views 中按钮的值。请看下图以更好地理解。

我用 Bootstrap 设计了表单。这是 HTML 表单的代码。

<form>
    {% csrf_token %}

    ...

    <p class='details-scrape'>Select the items you want to add to the list</p>
    <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off">
        Tomato
    </button>
    <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off">
        Eggs
    </button>
    <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off">
        Bread
    </button>
    <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off">
        Beans
    </button>
    <button type="button" class="btn btn-outline-primary" data-toggle="button" aria-pressed="false" autocomplete="off">
        Cheese
    </button>

    <button type="submit" class="btn btn-primary btn-block btn-lg mt-5">Submit</button>
</form>

这是我的views.py代码

def index(request):
    if request.method == 'POST':

        # ------------- New code will come here -----------------
        #access the values of the clicked buttons here...

        return redirect(index)

    else:
        return render(request, 'index.html')

【问题讨论】:

    标签: python django forms twitter-bootstrap django-views


    【解决方案1】:

    在 HTML 表单中,只有输入数据被传输到服务器。 但在这种情况下,您可以这样做:

    1. 为每个切换按钮添加隐藏输入。
    2. 在表单的“onsubmit”事件中调用 javascript 函数。
    3. 在函数中获取按钮的值。
    4. 将值插入隐藏输入(例如,将 ID 为“input1”的隐藏输入的值设置为 ID 为“btn1”的按钮的值)
    5. 提交表单。
    6. 现在您可以访问包含按钮值的隐藏输入值。

    【讨论】:

    • 你好。我添加了 hidden inputs 和 jquery 代码来填充按钮单击时的字段值。但是我无法使用此代码request.POST.get('tomato-input') 通过我的视图访问输入的值。这只是返回None。我做错了什么?
    • 如果您不向服务器发送密钥数据 django 将引发错误:找不到密钥。我认为您正在向服务器发送输入,但您无法使用 jquery 为隐藏输入设置值。如果问题未解决,请显示您的 js 代码和 html 表单
    猜你喜欢
    • 2022-09-30
    • 1970-01-01
    • 2012-05-23
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 2020-05-11
    相关资源
    最近更新 更多