【问题标题】:How can code be activated on click of a button in a Django view?单击 Django 视图中的按钮如何激活代码?
【发布时间】:2023-02-15 21:26:18
【问题描述】:

我有一个包含按钮的模板。

我在视图文件中有此模板的视图。

单击此按钮(位于模板中)时如何激活部分代码?

你怎样才能让它尽可能简单?

单击 Django 视图中的按钮如何激活代码?

def click_button_summ(request):
    context = {}
    if request.POST.get("button_table_summ") == "button_table_summ":
        ///code///
    return render(request, "click_button_summ.html", context)


    <div class="ui container">
        <div class="column">
            <button type="submit" class="ui button" name="button_table_summ" value="button_table_summ">Button</button>
        </div>
    </div>`

【问题讨论】:

  • 你应该改为if "button_table_summ" in request.POST。
  • 不幸的是我已经尝试过这没有用需要别的东西
  • 您共享的是您的实际代码吗?

标签: python django templates django-views


【解决方案1】:

在模板中:

<button id="choose-your-id-here" type="submit" class="ui button" name="button_table_summ" value="1">Button</button>

价值可以是你喜欢的任何东西,但是ensure所有按钮都有一个唯一的值(所以数字是最简单的——而且你实际上并不使用这个值)并且与名称不同。使用上面的解决方案,您可以在同一页面上有多个按钮:

<button id="choose-your-id-here" type="submit" class="ui button" name="button_table_foo" value="1">Button</button>

<button id="choose-your-id-here" type="submit" class="ui button" name="button_table_bar" value="2">Button</button>

并且,在您的一个视图(处理所有内容)中,每个视图都有特定的代码:

if request.POST.get("button_table_foo"):
    # code here specific to this button being pressed as form submission

if request.POST.get("button_table_bar"):
    # code here specific to this button being pressed as form submission

和/或你可以在你的模板中放置一个 formaction 来由不同的视图处理(当然只要你在你的 urls.py 中有那个视图):

<button id="choose-your-unique-id" type="submit" class="ui button" name="button_table_summ" value="1" formaction="{% url 'valid url-in-urls.py-here' %}>Button</button>

【讨论】:

    猜你喜欢
    • 2011-09-17
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2011-05-01
    相关资源
    最近更新 更多