如何检查用户是否是第一次访问页面 [英] How to check if the user is visiting the page for the first time

查看:54
本文介绍了如何检查用户是否是第一次访问页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我们如何知道用户是否是第一次访问该页面?从技术上讲,我们是否将访问模型的每个页面的访问次数存储在模型中(我使用的是django),还是可以遵循其他一些模式来简化操作?

In general how do we know if user is visiting the page for the first time? Technically, do we store the number of visits to each page in the Model(I am using django) or is there some other pattern that I could follow to ease up the operation.

我只是在寻找实现此目的的设计。

I m just looking for a design for implementing this.

推荐答案

我认为您将为此创建自己的机制。

I think you will have to create your own mechanism for this.

我将创建一个模型,用于存储每个网址和用户的首次访问,例如 FirstVisit 。然后,如果用户在视图中请求页面,则可以搜索 FirstVisit 中当前用户和url的条目,并确定这是否是他的第一次。之后,如果他还没有访问过,则将条目存储到 FirstVisit 模型中,因为他只是要获取页面的内容。

I would make a model storing first visits for every url and user called e.g FirstVisit. Then if a user requests a page in a view you can search if there is an entry in FirstVisit for current user and url and find out if it's his first time or not. After that, if he hasn't visited yet, you store the entry to the FirstVisit model, because he is just going to get the content of the page.

我将尝试编写代码:

#models.py

class FirstVisit(models.Model):
    url = models.URLField()
    user = models.ForeignKey('auth.User')


#views.py

def my_view(request):
   if not FisrtVisit.objects.filter(user=request.user.id, url=request.path).exists():
      #he visits for the first time
      #your code...
      FisrtVisit(user=request.user, url=request.path).save()

您可以创建一个装饰器,并在其中放置此功能。然后将装饰器添加到要存储此信息的任何视图中,并从装饰器中向该视图传递一个标志参数,以确定用户是否第一次在该视图中。

You can create a decorator and put in there this functionality. Then add the decorator to any view you want to store this information and from the decorator pass a flag argument to the view determining if user is there for the first time.

这篇关于如何检查用户是否是第一次访问页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆