【问题标题】:Send POST request to views.py from base.html template从 base.html 模板向 views.py 发送 POST 请求
【发布时间】:2020-11-02 04:39:07
【问题描述】:

我正在使用 django-notifications-hq 在网站的顶部导航栏中显示通知,该导航栏恰好位于基本模板文件 base.html 中。我在导航栏中有一个小按钮来设置要读取的通知,但我无法将 POST 请求发送到 views.py。有没有办法从网站上的任何地方将此 POST 请求发送到 view.py 中的特定函数?我已经阅读了有关上下文处理器的信息,但是当您想要将数据从视图发送到基本模板文件时,这似乎只会在相反的情况下有所帮助。

views.py 中的函数我想从 base.html 发送一个 POST 请求:

def mark_all_as_read(request):
    request.user.notifications.mark_all_as_read()


    return redirect('home') #ideally, just refresh the page the user is on but I can't figure that out either

base.html 表单我想从以下位置发送请求:

<ul class="dropdown-grid-menu" id="notice-link">
                    <a href="{% url 'messages' %}">
                      {% live_notify_list %}
                    </a>
                    <li>
                      <form method='POST'>
                      {% csrf_token %}
                      <br /><button class="btn btn-sm btn-primary" href="{% url 'mark_all_as_read' %}" type="submit" role="button">Mark Read</button>
                      </form>
                    </li>
                  </ul>

希望有一个简单的解决方案。谢谢!

编辑:URLS.py

path('mark_all_as_read', views.mark_all_as_read, name='mark_all_as_read'),

【问题讨论】:

  • 您只需为mark_all_as_read 添加一个urls.py 条目。然后您可以在所有模板中使用它(并从中调用它)
  • 所以我在我的 urls.py 中有这个,但我如何指定确切的功能? path('mark_all_as_read', views.mark_all_as_read, name='mark_all_as_read'),
  • views.mark_all_as_read 是服务于该视图的函数。当你想指定 exact function 时,我不确定你的意思
  • 这是因为当我提交表单时,它似乎没有到达views.py 中的mark_all_as_read 函数。不知道为什么它根本不发送 POST 请求。

标签: python django


【解决方案1】:

要指定要向其提交 POST 请求的端点/url/路径,您需要设置 form 标签的 action 属性

<form method="POST" action="{% url 'mark_all_as_read' %}">
    {% csrf_token %}
    <br />
    <input type="submit" class="btn btn-sm btn-primary" role="button">Mark Read</button>
</form>

【讨论】:

  • 就是这样!太感谢了。那么POST表单需要action属性,然后GET请求可以使用基本的href属性?
  • @winston forms 始终需要 action 属性,用于 GET 或 POST。如果您不提供action,表单将提交到当前网址
猜你喜欢
  • 2011-01-20
  • 2020-12-05
  • 2021-05-29
  • 2014-08-04
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
相关资源
最近更新 更多