I am having a viewcount
feature in my post of a small blog project which counts the number of times a particular blog has been viewed, but after viewing a particular blog, the value of the viewcount
remains unchanged until the entire page is refreshed. So, I am trying to figure out a way to refresh only that portion of the div
section which is containing the viewcount
value.
Here is my required portion of the html code:-
{% for post in posts %}
<article class="media content-section">
<div class="media-body">
<h2><a class="article-title" href="{% url 'post-detail' post.slug %}" onclick="ViewCountRefresh()">{{ post.title }}</a></h2>
<div class="article-metadata" id="viewcountrefresh">
<a class="mr-2" href="{% url 'blog-profile' name=post.author %}">{{ post.author }}</a>
<div class="float-right">
<small class="text-muted">Category</small>
<small class="text-muted">{{ post.date_posted }}</small>
</div>
<img style="height:19px; width:18px; float:right;" src="{% static "blog/viewicon.png" %}"><p id="viewcountrefresh" style="float: right; display: inline !important;">{{post.view_count}}</p></img>
</div>
<p class="article-content">{{ post.content|truncatechars:200|safe }}</p>
</div>
</article>
{% endfor %}
This is my views.py
file:-
class PostDetailView(DetailView):
model = Post
def get_object(self):
obj = super().get_object()
obj.view_count += 1
obj.save()
return obj
Here's the urls.py file:-
from django.urls import path
from .views import (
PostDetailView,
home,
)
urlpatterns = [
path("", home, name="blog-home"),
path("post/<slug:slug>/", PostDetailView.as_view(), name="post-detail"),
]
I am trying to refresh the content of the div section containing the id viewcountrefresh
so that when any blog is visited, and then I come back to my homepage I get the updated value of the viewcount
from the database.
Here is the js script:-
function ViewCountRefresh(){
...
...
...
}
I am a beginner in javascript & ajax, so having a hard time figuring out the code that would solve this problem.