Ryan Oh
Ryan Oh

Reputation: 657

How do I count number of clicks of links in for-loop in Django template tag?

So I have a Django application, where I upload one article per day (to be more precise, I provide title and subtitle of the article as well as its link, so the user can click the link to see the whole article). I have made this using for-loop in template tag, as shown below.

...
{% for item in articles %}
<div class="row">
    <a href="{{item.url}}" class="all-articles" target="_blank" rel="noopener noreferrer">
    <div class="col">
        <span class="title">{{item.title}}</span><br>
        <span class="subtitle"> | {{item.subtitle}}</span>
    </div>  
    </a>
</div>
{% endfor %}
...

Now I'd like to see the number of clicks of each article. But I have no idea on how to make it possible. Any idea?
Thank you very much in advance. :)

Upvotes: 2

Views: 939

Answers (1)

ruddra
ruddra

Reputation: 51988

For that, you need to write a view which will redirect you to the url, and in the mean time, count the click. For example(partially copy pasted from documentation):

You can use RedirectView for redirection:

from django.shortcuts import get_object_or_404
from django.views.generic.base import RedirectView

from articles.models import Article

class ArticleCounterRedirectView(RedirectView):
    permanent = False
    query_string = True

    def get_redirect_url(self, *args, **kwargs):
        article = get_object_or_404(Article, pk=kwargs['pk'])
        article.update_counter()
        return article.url

Then, add it to urls.py

from django.urls import path
from article.views import ArticleCounterRedirectView, ArticleDetail

urlpatterns = [
    path('counter/<int:pk>/', ArticleCounterRedirectView.as_view(), name='article-counter'),
]

Finally, update the template with following code:

<a href="{% url 'article-counter' item.pk %}" class="all-articles" target="_blank" rel="noopener noreferrer">

Upvotes: 4

Related Questions