在类Index(TemplateView)中使用request.user

时间:2016-08-21 05:43:21

标签: python django django-templates django-views django-rest-framework

我正在努力实现这个目标:

class Index(TemplateView):
    if request.user.role == 'admin':
        template_name = 'index/admin/index.html'
    elif request.user.role == 'ff':
        template_name = 'index/firefighter/index.html'
    else:
        template_name = 'index/dev/index.html'

@method_decorator(ensure_csrf_cookie)
def dispatch(self, *args, **kwargs):
    return super(Index, self).dispatch(*args, **kwargs)

我不知道如何实施它...任何帮助?此代码不起作用有错误:“未定义的名称'请求'”

1 个答案:

答案 0 :(得分:2)

使用get_template_names()方法设置模板:

from django.utils.decorator import method_decorator

class Index(TemplateView):
    def get_template_names(self, *args, **kwargs):
        roles_urls = {'admin': 'index/admin/index.html',
                      'ff': 'index/firefighter/index.html'}
        default = 'index/dev/index.html'
        return [roles_urls.get(self.request.user.role, default)]

    @method_decorator(ensure_csrf_cookie)
    def dispatch(self, *args, **kwargs):
        return super(Index, self).dispatch(*args, **kwargs)