【问题标题】:Display intro video first visit only Django仅显示介绍视频首次访问 Django
【发布时间】:2019-04-26 16:20:33
【问题描述】:

我有一个 Django 应用程序,它需要显示一个视频,以便进入网站。我只希望它在初次访问时执行此操作,而不是每次用户刷新时执行此操作。我觉得会话与此有关,但我不确定。谢谢!

【问题讨论】:

  • 如果用户已登录,您可以在服务器数据库中的用户记录中存储“hasSeenIntroVideo”。如果用户未登录,您可以将其存储在 Session 中,这将持续到该用户离开,下次他在浏览器中启动您的网站时,他将再次看到视频(全新的 Session)。如果您只希望用户观看一次视频(每个用户/浏览器组合),您可以使用 Cookie 在他的浏览器中存储“hasSeenIntroVideo”,然后在他下次访问您的网站时读取该 cookie。
  • 您好,感谢您的回复。你能举例说明如何做到这一点吗?谢谢!

标签: javascript django frontend


【解决方案1】:

我认为最好将此标志直接放在您的数据库中。您可以在您的用户模型(如果您使用自定义用户)或与UserOneToOne 关系的模型中放置一个字段。例如:

class Profile(models.Model):
    user = models.OneToOneField(User)
    has_seen_intro = models.BooleanField(default=False)

并像这样从视图中将此信息发送到模板,例如:

class HomeView(TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
       context = super(HomeView, self).get_context_data(**kwargs)
       profile = self.request.user.profile
       if not profile.has_seen_intro:
           context['show_intro'] = True
           profile.has_seen_intro = False
           profile.save()
       # or  use user.has_seen_intro if you have custom model
       return context

并像这样更新模板

{% if show_intro %}
    // intro video codes
{% endif %}

更新

对于匿名用户,请尝试这样:

class HomeView(TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
       context = super(HomeView, self).get_context_data(**kwargs)
       if self.request.user.is_authenticated:
            profile = self.request.user.profile
            if not profile.has_seen_intro:
               context['show_intro'] = True
               profile.has_seen_intro = False
               profile.save()
       else:
            if not self.request.session.get('has_seen_intro', True):
                 self.request.session['has_seen_intro'] = False
                 context['show_intro'] = True
       return context

【讨论】:

  • 这适用于登录用户,但我所有的用户都是匿名的
猜你喜欢
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
相关资源
最近更新 更多