I am trying to write a Django application and I am stuck at how I can call a view function when a button is clicked.
In my template, I have a link button as below, when clicked it takes you to a different webpage:
<a target="_blank" href="{{ column_3_item.link_for_item }}">Check It Out</a>
When the button is clicked, I also want to call a Django view function (along with re-direct to a target website). The view function increments the value in the database which stores the number of times the button is clicked.
The column_3_item.link_for_item
is a link to an external website (e.g. www.google.com). Right now when that button is clicked, it opens a new window which takes you to the google website.
What I would like to do is to call a Django view function also when the button is clicked which updates the database without refreshing the page. How I can achieve this?
This question is related to
python
django
django-templates
django-views
The following answer could be helpful for the first part of your question:
There are 2 possible solutions that I personally use
1.without using form
<button type="submit" value={{excel_path}} onclick="location.href='{% url 'downloadexcel' %}'" name='mybtn2'>Download Excel file</button>
2.Using Form
<form action="{% url 'downloadexcel' %}" method="post">
{% csrf_token %}
<button type="submit" name='mybtn2' value={{excel_path}}>Download results in Excel</button>
</form>
Where urls.py should have this
path('excel/',views1.downloadexcel,name="downloadexcel"),
Source: Stackoverflow.com