I want to do the following: every time a user enters an article, it increments the visit by +1, but only the first time the user logs in, so I have to save the fact that the user has already entered the page in some place. But I'm not using authentication or anything like that.
I know I can use javascript to store in LocalStorage, but I still do not know how to work with APIS in the back end.
What's the easiest way to do this on the backend?
Currently the function that increments is as below. NOTE: I create a new object instead of using something like "instance.visits + = 1" because I need to save the date of each visit to filter the posts with more visits in a certain period of time, and that was the only way I got it.
class ArticlePage(Page):
# ....
def serve(self, request, *args, **kwargs):
request.is_preview = getattr(request, 'is_preview', False)
self.views.create(date=datetime.datetime.now())
self.save()
print(self.views.all().count())
return TemplateResponse(
request,
self.get_template(request, *args, **kwargs),
self.get_context(request, *args, **kwargs)
)
class ArticlePageViews(models.Model):
article = models.ForeignKey(
ArticlePage,
on_delete=models.CASCADE,
related_name='views'
)
date = models.DateTimeField()
def __str__(self):
return f'{self.date}'