首页 > 解决方案 > 从 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'),

标签: pythondjango

解决方案


要指定要向其提交 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>

推荐阅读