python - 从 base.html 模板向 views.py 发送 POST 请求
问题描述
我正在使用 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'),
解决方案
要指定要向其提交 POST 请求的端点/url/路径,您需要设置标签的action
属性form
<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>
推荐阅读
- python - 如何在 pandas DataFrame 子类中定义实例属性?
- php - Laravel 的符号链接存储链接无法按预期工作
- javascript - 如何使用 jquery 使 .active 类动态化,而不仅仅是关注第一个?
- javascript - 更新在另一个对象内部使用的对象
- woocommerce - WooCommerce 中的 ACF 图像
- image - 如何在 Docker 构建时删除所有关联的容器和图像
- python - 复制 xPath 位置后无法通过 Selenium 定位元素错误
- amazon-ec2 - aws ec2 在 WinSCP 上以 root 身份登录 - 收到过大 (... B) SFTP 数据包。支持的最大数据包大小为 102400 B
- node.js - 如何访问这个 ES5 类中的父方法?
- ethereum - 当我从 remix 部署合同时,geth 显示“合同创建代码存储不足”