【问题标题】:Django + non-form buttons: How to connect a non-form button or link to django's python code in views.py?Django + 非表单按钮:如何在views.py 中连接非表单按钮或链接到django 的python 代码?
【发布时间】:2019-06-07 14:27:18
【问题描述】:

如何将用 HTML 编写的非表单按钮或链接连接到 Django 中的 python 代码?具体来说,假设我在 HTML 中有一个使用 href="/some-link" 重定向页面的按钮。例如,当按下这样的按钮时,我如何在 Django 中将特定信息保存到会话(即保存按下哪个按钮)?

基本上,我想在views.py中做类似以下的事情:

if request.POST['form-type'] == u"purchase-button":
# save some info before redirecting the page
   request.session['some-variable'] = 'the-purchase-button-was-pressed'
   return redirect('some-link')

...除了这不是表格,所以我实际上不能这样做。

我会以某种方式修改以下 HTML 吗?

<a href="/some-link">Purchase</a>

总的来说,我对 Django 和 Web 开发有点陌生,因此非常感谢任何帮助。

(基本上,我有以下链接中提出的确切问题,但我对答案并不满意:Django: How to trigger a session 'save' of form data when clicking a non-submit link

编辑:

我最终使用了一个空白表单,如下所示,它让我可以参考下面的 python 代码中按下了哪个按钮,而无需用户实际填写信息。

在 HTML 中:

 <form id="purchase" action="" method="post" name="purchase">
 {% csrf_token %}

     <input type="hidden" name="form-type" value="purchase" /> <!-- set type -->
     <input type="hidden" name="form-id" value="{{ item.id }}" /> <!-- set item ID -->

     <button name="purchase" type="submit" id="purchase-submit" data-submit="...Sending">Purchase</button>

 </form> 

在views.py中:

if request.POST['form-type'] == u"purchase":
    # this allows me to call the corresponding item by its ID
    desired_item = StoreItem.objects.get(id=str(request.POST['form-id']))

    # this saves information about the desired item 
    request.session['item_name'] = str(desired_item.title)
    request.session['item_id'] = str(request.POST['form-id'])
    request.session['amount'] = str(desired_item.price)

    return redirect('shipping')

这允许我从按钮获取信息并在views.py 中使用它,即使用户没有输入任何其他信息。

【问题讨论】:

  • 我不明白你在问什么。链接不是按钮,除了 URL 本身之外,没有与链接关联的数据。那么你会节省什么?

标签: html django django-sessions htmlbutton


【解决方案1】:

我会将其作为带有参数的 GET 请求发送,将按钮设置为重定向到“/some-link/?button=PURCHASE”。

因此,在 views.py 中,您将拥有“request.GET['button']”,它的值将是“PURCHASE”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-05
    • 2014-03-21
    • 2020-11-28
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    相关资源
    最近更新 更多