Hassan Baig
Hassan Baig

Reputation: 15824

Keeping count of clicks of <a> tag (non-JS)

In a Django mobile web app I'm building, I'm using the sms html tag in one particular template. I.e. the typical <a href="sms:/* phone number here */?body=/* body text here */">Link</a>. Every time the user presses Link, they're redirected to their phone's default SMS app with a prepopulated message.

How can one implement a counter that increments every time a user clicks Link? The challenge is to solely use Python/Django (server-side), no JS.

Upvotes: 2

Views: 470

Answers (1)

v1k45
v1k45

Reputation: 8250

You can implement a model to track clicks on Link. To track, you can create something like redirection view which redirects to sms URI after tracking click.

A basic example would be:

from django.http.response import HttpResponseRedirect, HttpResponseRedirectBase

HttpResponseRedirectBase.allowed_schemes += ['sms']

class SMSRedirect(HttpResponseRedirect):
    pass

def track_count(request):
    phone = request.GET.get('phone', '')
    body = request.GET.body('body', '')
    link = build_sms_link(phone, body)
    link.hits += 1
    link.save()
    return SMSRedirect(link.url)

By default HttpResponseRedirectBase does not allow non-web schemes/protocols. You can make it allow by monkey-patching its allowed schemes list.

Upvotes: 3

Related Questions