Django 1.8 (Python 3.4):使用基于 Class 的视图根据用户授权显示不同的模板

Django 1.8 (Python 3.4): Show different templates based on user authorization with Class-Based Views

我想要一个基于 Class 的视图 'homepage'。当用户访问 'homepage':

如果用户是访客,则调用访客函数 如果用户已登录,则调用登录函数

然后调用的函数设置适当的模板和上下文。

这是正确的做法吗?如果是这样怎么办?我找到的文档仅通过函数视图对此进行了详细说明。

谢谢!

你知道吗,你的问题真的很开放。有很多不同的方法可以做到这一点。

我可能会继承 TemplateView,覆盖 dispatch 方法以根据场景设置不同的模板。

为了弄清楚您的逻辑如何适应各种 CBV,我推荐 Classy Class-Based-Views 资源,这样您就可以看到在何处调用了哪些方法。

我会覆盖 get_template_names to set the template name, and get_context_data to set the context data. You can access the user with self.request.user, and check whether they are logged in with the is_authenticated() 方法。

class HomepageView(TemplateView):
    def get_context_data(self, **kwargs):
        """
        Returns a different context depending
        on whether the user is logged in or not
        """
        context = super(HomepageView, self).get_context_data(**kwargs)
        if self.request.user.is_authenticated():
            context['user_type'] = 'logged in'
        else:
            context['user_type'] = 'guest'
        return context

    def get_template_names(self):
        """
        Returns a different template depending
        on whether the user is logged in or not
        """
        if self.request.user.is_authenticated():
            return 'logged_in_homepage.html'
        else:
            return 'guest_homepage.html'

请注意,我已经覆盖了 TemplateView 的不同方法来自定义功能,而不是为来宾调用一种方法或为登录用户调用另一种方法来执行所有操作。如果你真的想调用一个方法来完成所有的事情,那么使用函数视图可能会更好。