django - 使用基于类的 View (CBV) Django 2.1 Python 重定向页面

标签 django python-3.x redirect django-class-based-views

我想根据用户的角色将他们定向到特定页面。我想在基于类的 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'))

我知道 RedirectView。但是,如何获取 CBV 中的请求,以便像 request.user.role 中那样获取 user.role?我知道我可以在 CBV 内的某些函数中获取 user.role,如下所示:

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

如何在 CBV 中的 get_context_data() 之外访问 user_role?

最佳答案

RedirectView [Django-doc]中,您不需要实现 get_context_data 函数,URL 由 get_redirect_url method [Django-doc] 确定,因此您可以将其实现为:

class HomeRedirectView(RedirectView):

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

url attribute [Django-doc]仅当 URL 是静态时才设置,但您可以在内容非静态的情况下实现 get_redirect_url

关于django - 使用基于类的 View (CBV) Django 2.1 Python 重定向页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53991119/

相关文章:

jquery - 将 jquery 与 django Rest api 一起放置

django - 重定向到/admin/login/导致 302

python - 如何判断某些源代码中导入了哪些模块?

.htaccess - htaccess mod_rewrite 和 301 重定向到友好的 url

redirect - pfsense haproxy 重定向与 url 不匹配

javascript - IE8 Json问题

python - 为什么需要在 Django admin 中同时注册应用程序名称和应用程序管理员名称?

python - 生成规则 30 元胞自动机的行

python - 打字:定义一个只能是某些字符串的类型?

java - 拦截器 preHandle() 未重定向到 login.html