Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

python - How do I call a Django function on button click?

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?

question from:https://stackoverflow.com/questions/15341285/how-do-i-call-a-django-function-on-button-click

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).

<html>
    <head>
        <title>An example</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            function call_counter(url, pk) {
                window.open(url);
                $.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
                    alert("counter updated!");
                });
            }
        </script>
    </head>
    <body>
        <button onclick="call_counter('http://www.google.com', 12345);">
            I update object 12345
        </button>
        <button onclick="call_counter('http://www.yahoo.com', 999);">
            I update object 999
        </button>
    </body>
</html>

Alternative approach

Instead of placing the JavaScript code, you can change your link in this way:

<a target="_blank" 
    class="btn btn-info pull-right" 
    href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
    Check It Out
</a>

and in your views.py:

def YOUR_VIEW_DEF(request, pk):
    YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
    return HttpResponseRedirect(request.GET.get('next')))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...