Article views are a must-have number on any social networking site, and it’s important enough to know.

Bloggers can use page views to gauge the popularity of an article, and readers can use page views to screen for higher-quality articles.

However, getting an accurate count of pageviews is not easy:

  • Some types of requests should not be counted as views, such as redirects after the author has viewed or edited the article himself;
  • Due to the large number of users, the data of page views are updated rapidly all the time, which will bring great pressure to the database. As a result, many large web sites use in-memory databases such as Redis to assist storage with very fast read/write speeds.

Because our project is a blog website, rough statistics can be done, there is not so much user pressure, so the design is much simpler.

model

Page views, as data available to every blog post, need to be stored in a field.

Therefore, modify the model of the article:

article/models.py

...
class ArticlePost(models.Model):. total_views = models.PositiveIntegerField(default=0)...Copy the code
  • PositiveIntegerFieldIs a field used to store positive integers
  • default=0Set the initial value to start at 0

Don’t forget to migrate the database after you modify it, otherwise the changes won’t take effect.

Since the new fields set their initial values, the migration should be smooth:

(env) E:\django_project\my_blog>python manage.py makemigrations
Migrations for 'article':
  article\migrations\0003_articlepost_total_views.py
    - Add field total_views to articlepost
Migrations for 'userprofile':
  userprofile\migrations\0002_auto_20181227_2041.py
    - Alter field avatar on profile
    - Alter field user on profile

(env) E:\django_project\my_blog>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, article, auth, contenttypes, sessions, userprofile
Running migrations:
  Applying article.0003_articlepost_total_views... OK
  Applying userprofile.0002_auto_20181227_2041... OK
Copy the code

A list of the template

To see the effect, I’ll write the template file first.

Where do I need to display pageviews? It’s easy to think of a list of articles. Modify the template for the article list:

templates/article/list.html

...

<div class="card-footer">
    <! -- Existing code -->
    <a href="{% url 'article:article_detail' article.id %}"
        class="btn btn-primary">Read this article</a>

    <! -- Display pageviews -->
    <span>
        <small class="col align-self-end" style="color: gray;">{{article. Total_views}}</small>
    </span>

</div>.Copy the code

The number of page views is displayed next to “Read this article”.

Some students feel that the display here is not good, please modify the code, put it in their most satisfactory place. (Familiarize yourself with Bootstrap!)

Details of the template

In addition to the list of articles, the page views are usually displayed on the details page.

In addition, for convenience, there is no permission management in the previous study, so that any user can modify or delete all articles:

This is definitely not going to work, and this serious error must be fixed.

Modify the article/detail.html template file:

templates/article/detail.html

...
<! -->
<div class="container">
    <div class="row">.<div class="col-12 alert alert-success">
            <div>Author: {{article. Author}} {% if user == article. Author %} ·<a href="#" onclick="confirm_delete()">Delete articles</a>
                    · <a href="{% url "article:article_update" article.id%} ">Edit the articles</a>
                {% endif %}
            </div>
            <div>{{article. Total_views}}</div>
        </div>.</div>.Copy the code

The modifications include:

  • Confirm that the current login user is the author of the article, and then the “Delete article” and “Edit Article” links are displayed
  • Display page views

The modified page is as follows:

In the image above, the link to modify the article is not rendered due to a discrepancy between the author and the logged-in user. If the logged-in user is the author, they will display normally again.

This approach prevents most “good users” from illegally modifying data. But what if a “bad user” just types in a URL address to wreak havoc? So it’s not enough just to rely on the front page to authenticate.

view

The pageviews are now displayed correctly, but since no processing has been done, they remain 0. We want to increase page views by 1 every time a user visits the details page.

Modify article_detail() as follows:

article/views.py

...
def article_detail(request, id):
    article = ArticlePost.objects.get(id=id)
    
    # Views +1
    article.total_views += 1
    article.save(update_fields=['total_views'])...Copy the code

Update_fields =[] specifies that the database only updates the total_views field, optimizing the execution efficiency.

To test this, you can count page views:

View authentication

As mentioned earlier, authentication in the template alone is not enough; the user must be authenticated again in the back-end business logic.

Modify article_update() to update the view of the article:

article/views.py

...
Remind users to log in
@login_required(login_url='/userprofile/login/')
def article_update(request, id):
    # Existing code
    article = ArticlePost.objects.get(id=id)

    # Filter non-author users
    ifrequest.user ! = article.author:return HttpResponse("Sorry, you have no right to change this article.")...Copy the code

Authentication is performed twice in the view:

  • login_requiredDecorator filters users who are not logged in
  • ifStatement filters users who are logged in but not the author

By re-authenticating the identity in the business logic, it completely prevents malicious users from taking advantage of it.

In addition to updating the view of an article, deleting an article should do the same. Please modify and test it yourself.

conclusion

This chapter completes the simple function of counting page views, and verifies the user’s identity in the front and back end.

In the next chapter, we’ll learn about a feature that is closely related to page views: search for the most popular articles.

  • If you have any questions please leave a message on Doucet’s personal website and I will reply as soon as possible.
  • Or Email me a private message: [email protected]
  • Project code: Django_blog_tutorial

Please indicate the source of reprint.