简体   繁体   中英

Send POST request to views.py from base.html template

I'm using django-notifications-hq to display notifications in the top navbar of the website, which happens to be located in the base template file, base.html. I have a small button in the navbar to set notifications to read but I'm having trouble sending the POST request to the views.py. Is there a way to send this POST request from anywhere on the website to a specific function in views.py? I've read about context processors but that only seems to help in opposite scenarios when you want to send data from views to the base template file.

Function in views.py I want to send a POST request to from base.html:

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 form I want to send a request from:

<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>

Hoping there is an easy solution. Thanks!

EDIT: URLS.py

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

To specify the endpoint/url/path that you want to submit a POST request to you need to set the action attribute of the form tag

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM