表格中显示字典的两个按钮不起作用

发布于 2025-01-24 20:06:51 字数 806 浏览 1 评论 0原文

我想在模板表单中使用两个按钮,并在功能中运行两个操作。 当我只使用按钮时,django运行,但是当我在代码中添加执行2个操作时,它停止工作 从视图中: def结果(请求): num1 = int(request.get [“ num1”]) num2 = int(request.get [“ num2”])

if 'add' in request.POST:
    res = num1 + num2

if 'sub' in request.POST:
    res = num1 - num2

return render(request, 'home/result.html', {'result': res})

在模板中名为clt的

        <form action="result" >
            Enter 1st number : <input type="text" name="num1"><br>
            Enter 2st number : <input type="text" name="num2"><br>

            <button type="submit" name="subscribe">Subscribe</button>
            <button type="submit" name="unsubscribe">Unsubscribe</button>

        </form>

模板命名结果 结果 : {{ 结果 }}

I want to use two buttons in a template form and run two action in a function.
when I omit if with only a button, django runs , but when I add if in the codes to execute 2 action , it stops working
in view:
def result(request):
num1 = int(request.GET["num1"])
num2 = int(request.GET["num2"])

if 'add' in request.POST:
    res = num1 + num2

if 'sub' in request.POST:
    res = num1 - num2

return render(request, 'home/result.html', {'result': res})

in template named clt

        <form action="result" >
            Enter 1st number : <input type="text" name="num1"><br>
            Enter 2st number : <input type="text" name="num2"><br>

            <button type="submit" name="subscribe">Subscribe</button>
            <button type="submit" name="unsubscribe">Unsubscribe</button>

        </form>

in template named result
result :
{{ result }}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落花浅忆 2025-01-31 20:06:51

在上方的“如果”测试的代码中,您的名称与给出的按钮不匹配。尝试:

if 'subscribe' in request.POST:
    res = num1 + num2

if 'unsubscribe' in request.POST:
    res = num1 - num2

格式打破了您的代码,看来您正在使用这两个变量。如果有效,则不用担心,但是通常应通过request.post.get ['num1']获得已发布的数据

In the code above your 'if' test does not match the name you have given the buttons. Try:

if 'subscribe' in request.POST:
    res = num1 + num2

if 'unsubscribe' in request.POST:
    res = num1 - num2

The formatting broke on your code, it looks like you are using GET to get the two variables. If that's working, no worries, but normally form posted data should be gotten by request.POST.get['num1']

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文