HelloGitHub- dream chasers
The sample code in this article has been synchronously updated to the HelloGithub-Team repository
Keeping an accurate record of how much an article is read is a complex issue, but for our blog, it’s not necessarily that accurate. So we use a simple but effective way to keep track of how many blog posts are read: each time a post is viewed, the number of views is +1, which is called PV (Page View). Simple and crude, but efficient and practical.
Add new fields
To keep track of the number of views for an article, you need to add a field to the database table for the article to store the number of views. So add a view field to the blog post model:
blog/models.py
class Post(models.Model):
#... Other existing fields
# Add new views field to record reading volume
views = models.PositiveIntegerField(default=0, editable=False)
Copy the code
Note that the type of the views field is PositiveIntegerField. The value of this field can only be a positive integer or 0 because the read value cannot be negative. The value of views is 0 during initialization. Setting the editable parameter to False will not allow django Admin to edit the contents of this field behind the scenes. Because reading should be measured by the number of times it is accessed, not artificially modified.
Add model method
Once the user accesses an article, the value of views should be +1. This process is best done by the Post model itself, so add a custom method to the model:
blog/models.py
class Post(models.Model):
#... Other existing fields
# Add new views field to record reading volume
views = models.PositiveIntegerField(default=0)
#... Other existing modeling methods
def increase_views(self):
self.views += 1
self.save(update_fields=['views'])
Copy the code
The increase_views method first increases the value of its own views field by +1 (while the value in the database has not changed yet) and then calls the save method to save the changed value to the database. Note that the update_fields parameter is used to tell Django to update only the views field values in the database for efficiency.
You might worry that if two people access an article at the same time, will changing the value of the read field in the database conflict? Don’t worry, we don’t measure exactly how many people read, and personal blogs don’t usually have a lot of traffic, so the error from the occasional conflict is negligible.
Migrating a Database
Once you change the model, you need to migrate the database so that Django reflects the changes to the database. Run the following two commands in the project root directory:
$ pipenv run python manage.py makemigrations
$ pipenv run python manage.py migrate
Copy the code
For details on how to migrate a database, see Django Migrating and Manipulating a Database.
Modifying view functions
When a user requests access to an article, the view function that handles the request is detail. Once the view function is called, the article has been accessed once, so we modify the detail view function to make the article +1 read when the view function is called.
blog/views.py
def detail(request, pk):
post = get_object_or_404(Post, pk=pk)
# Reading +1
post.increase_views()
md = markdown.Markdown(extensions=[
'markdown.extensions.extra'.'markdown.extensions.codehilite'.Remember to introduce TocExtension and Slugify at the top
TocExtension(slugify=slugify),
])
post.body = md.convert(post.body)
m = re.search(r'<div class="toc">\s*<ul>(.*)</ul>\s*</div>', md.toc, re.S)
post.toc = m.group(1) if m is not None else ' '
return render(request, 'blog/detail.html', context={'post': post})
Copy the code
You simply call the increase_views method of the model in the view function.
Display the readings in the template
To display readings in a template, just like any other field, you use template variables. Use {{post.views}} template variables where appropriate. Here we are going to change two places, index. HTML and detail.html.
templates/blog/index.html
<div class="entry-meta">.<span class="views-count"><a href="{{ post.get_absolute_url }}">{{post.views}} Read</a></span>
</div>
Copy the code
templates/blog/detail.html
<div class="entry-meta">.<span class="views-count"><a href="#">{{post.views}} Read</a></span>
</div>
Copy the code
Each time a user accesses the details of an article, the value of the views record will be +1, thus achieving a rough count of the number of views read.
“Explain Open Source Project series” — let the people who are interested in open source projects not be afraid, let the initiator of open source projects not be alone. Follow along as you discover the joys of programming, use, and how easy it is to get involved in open source projects. Welcome to leave a message to contact us, join us, let more people fall in love with open source, contribute to open source ~