V
V
Vlad2021-02-23 00:43:40
Django
Vlad, 2021-02-23 00:43:40

How to display the news view counter correctly?

Good afternoon!

I decided to add an attribute of the counter for viewing a specific news to the model: And I began to figure out how to make the counter increase when viewing a specific news. I thought of the following:views = models.IntegerField(default=0)

DetailView
class ViewNews(DetailView):  
    model = News
    context_object_name = 'news_item'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['unwanted_link'] = 'news/news_detail.html'
        context['news_item'].views += 1
        context['news_item'].save()
        return context

those. here it is my attribute increases each time you view a particular news item. And it works in principle. But then I read somewhere that this method may not work correctly in multi-threaded mode. I'm not familiar with this yet, but I understand that we are talking about multiple simultaneous requests to the server. And it is proposed to use the method with the F function. I redid it and it worked out . But the whole problem is that in the news template, when I display this variable as {{ news_item.views }} , then it is displayed for me , although the counter changes in the database itself. Can you please tell me how to display the number in the template? Thank you! context['news_item'].views += 1


context['news_item'].views = F('views') + 1
F(views) + Value(1)


Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-02-23
@Vlad1987

Simple and efficient way to count pageviews in django?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question