Redirect page with Class Based View (CBV) Django 2.1 Python

Viewed 1094

I want to direct users to a specific page based on their role. I'd like to implement something like this in a class based view.

def home_redirect(request):
    user_role = Profile.objects.get(user = request.user).role
    if user_role in internal_users:
        return redirect(reverse_lazy('home'))
    else:
        return redirect(reverse_lazy('event_list'))

I am aware of RedirectView. But how can I grab the request in a CBV in order to get the user.role as in request.user.role? I know I can get the user.role in certain functions within a CBV by like so:

class HomeRedirectView(RedirectView):
    def get_context_data(self, **kwargs):
        context = super(HomeRedirectView, self).get_context_data(**kwargs)
        context['current_user'] = Profile.objects.get(user = self.request.user)
        user_role = context['current_user'].role
        return context

    #Can't access user_role but if I could I would do something like this
    if user_role in internal_users:
        url = reverse_lazy('home')
    else:
        url = reverse_lazy('event_list')

How can I access user_role outside of get_context_data() in a CBV?

1 Answers

In a RedirectView [Django-doc], you do not need to implement a get_context_data function, the URL is determined by the get_redirect_url method [Django-doc], so you can implement this as:

class HomeRedirectView(RedirectView):

    def get_redirect_url(self, *args, **kwargs):
        user_role = Profile.objects.get(user=self.request.user).role
        if user_role in internal_users:
            return reverse('home')
        else:
            return reverse('event_list')

The url attribute [Django-doc] is only set if the URL is static, but you thus can implement get_redirect_url in case the content is non-static.

Related