Django blog development tutorial 16 – statistics of Article Reading

Time:2020-3-25

How to accurately record the reading amount of an article is a complex problem, but for our blog, it is not necessary to record it so accurately. Therefore, we use a simple but effective way to record the reading amount of blog articles: every time an article is viewed, its reading amount + 1, that is, the so-called PV (page view) number of article pages. Although simple and rough, it is efficient and practical.

Add new field

In order to record the page views of an article, you need to add a new field in the database table of the article to store the page views. So add a new blog post modelviewsField:

blog/models.py

class Post(models.Model):
    #... other existing fields
    #New views field record reading
    views = models.PositiveIntegerField(default=0)

Be carefulviewsThe type of field isPositiveIntegerField, values of this type are only allowed to be positive integers or 0, because reading cannot be negative. Initialization timeviewsThe value of is 0.

Add model method

Once a user visits an article, they shouldviewsThe best way to do this is byPostThe model completes itself, so add a custom method to the model:

blog/models.py

class Post(models.Model):
    #... other existing fields
    #New views field record reading
    views = models.PositiveIntegerField(default=0)
    
    #... other existing model methods
    
    def increase_views(self):
        self.views += 1
        self.save(update_fields=['views'])

increase_viewsMethod firstviewsThe value of the field is +1 (when the value in the database has not changed), and then called.saveMethod to save the changed value to the database. Note that it is used hereupdate_fieldsParameter to tell Django to update only the databaseviewsField to improve efficiency.

You may be worried about the conflict when two people access an article at the same time and change the value of the reading field in the database? In fact, we don’t need to worry about the fact that we do not accurately count the reading volume, and the traffic of personal blogs is usually not very large, so the data error caused by occasional conflicts can be ignored.

Migrating databases

Once you change the model, you need to migrate the database so that Django can reflect the changes into the database. Activate the virtual environment and run the following two commands:

python manage.py makemigrations
python manage.py migrate

For database migration, please refer to Django’s Translation: migration database model.

Modify view functions

When a user requests access to an article, the view function that processes the request isdetail。 Once the view function is called, the article is accessed once, so we modifydetailView function, let the accessed article read + 1 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()
    
    post.body = markdown.markdown(post.body,
                                  extensions=[
                                      'markdown.extensions.extra',
                                      'markdown.extensions.codehilite',
                                      'markdown.extensions.toc',
                                  ])
    form = CommentForm()
    comment_list = post.comment_set.all()
    context = {'post': post,
               'form': form,
               'comment_list': comment_list
               }
    return render(request, 'blog/detail.html', context=context)

That is, call the model only in view function.increase_viewsMethod.

Show reading in template

Just use the template variable to display the amount of reading in the template as well as other fields. That is, the {post. Views}} template variable is used where the template is appropriate. Here we modify two places respectively, index.html and detail.html.

templates/blog/index.html

<div class="entry-meta">
  ...
  < span class = "views count" ></a></span>
</div>
templates/blog/detail.html

<div class="entry-meta">
  ...
  < span class = "views count" ></a></span>
</div>

OK, so that when the user visits the details of an article,viewsThe recorded value will be + 1, so as to achieve the purpose of rough statistics of reading.

summary

The code for this chapter is located in: step16: record post views.

If you have problems, please ask for help in the following ways.

  • Leave a message in the blog comment area of the statistics article reading – dreamers.

  • Send a detailed description of the problem by email to django[email protected], and reply within 24 hours.

For more Django tutorials, visit the dreamers blog.