Alex cueto Alex cueto - 3 months ago 9
Python Question

Use request.user in class Index(TemplateView)

i'm trying to implement this:

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)


And i don't have idea that how implement it... Any help? This Code not work have the error: "Undefined name 'request' "

Answer

Set your template in the get_template_names() method:

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)
Comments