How do I call a Django function on button click

0 votes

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.

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?

Jun 23, 2020 in Python by kartik
• 37,530 points
26,276 views

1 answer to this question.

0 votes

Hello @kartik,

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"),

Hope this is helpful!

answered Jun 23, 2020 by Niroj
• 82,820 points

Related Questions In Python

0 votes
1 answer

How do I build a website with referral link on Django?

simple solution.. import hashlib Refferal(Model): user ...READ MORE

answered Nov 12, 2020 in Python by Gitika
• 65,950 points
690 views
0 votes
1 answer
0 votes
0 answers
0 votes
1 answer

How do I read a file on only read only mode in python?

Hey @David! TRy something like this: campaign_data = ...READ MORE

answered Jun 20, 2019 in Python by Jason
223 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,820 points
971 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,820 points
436 views
0 votes
1 answer

How do I add a link from the Django admin page of one object to the admin page of a related object?

Hello @kartik, Set show_change_link to True (False by default) in your inline ...READ MORE

answered Jun 12, 2020 in Python by Niroj
• 82,820 points
3,980 views
0 votes
1 answer

How do I clone a Django model instance object and save it to the database?

Hello @kartik, Just change the primary key of ...READ MORE

answered Jun 22, 2020 in Python by Niroj
• 82,820 points
1,668 views