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,510 points
59,322 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,880 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,910 points
2,153 views
0 votes
1 answer
0 votes
1 answer
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
569 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,880 points
2,080 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,880 points
1,226 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,880 points
9,934 views
0 votes
1 answer

How to call function that takes an argument in a Django template?

Hello @kartik, You cannot call a function that ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
12,447 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP