【问题标题】:Render or redirect when user role is specified指定用户角色时呈现或重定向
【发布时间】:2015-08-12 06:59:21
【问题描述】:

我正在使用 django 构建应用程序(请注意,我对 django 非常陌生)。我想从这个现有视图添加重定向。

视图内的对象:

from core.views import generic

class ListViewPublic(generic.ListView):
    pass

class BookListView(ListViewPublic):
    model = Book

    def get_queryset(self):
        filter_kwargs = {
            'status': Book.STATUS.public,
        }
        return Book.objects.filter(**filter_kwargs)

    def get_context_data(self, **kwargs):
        context = super(BookListView, self).get_context_data(**kwargs)
        form = SearchForm(load_all=True)
        context.update({'form': form})
        return context

例如

  • 鉴于用户未登录,它应该呈现页面
  • 鉴于用户有 reader 作为其角色,它应该呈现页面
  • 鉴于用户有 author 作为其角色,它应该被重定向到 /author url

我怎样才能实现这种行为?

【问题讨论】:

    标签: django django-views django-permissions


    【解决方案1】:

    您可以使用login_required 装饰器。对于您的自定义需求,例如应该重定向到 /author,您必须创建自定义装饰器。像这样。

    from django.utils.decorators import method_decorator
    from django.template import RequestContext, Context
    from django.http import HttpResponseRedirect
    from django.shortcuts import render_to_response, redirect, render
    
    def custom_login_required(f):
    
        def wrap(request, *args, **kwargs):
            """
               this will check user is logged in , if not it will redirect to login page
            """
            if request.user.is_authenticated() and request.user.user_profile.role=='author':
                return HttpResponseRedirect('/author')
            else:
                return render_to_response('index.html', locals(), context_instance=RequestContext(request))
            return f(request, *args, **kwargs)
    
        wrap.__doc__ = f.__doc__
        wrap.__name__ = f.__name__
        return wrap
    

    并在 get_context_data 上面写下类似的内容。

    @method_decorator(custom_login_required)
    def get_context_data(self, **kwargs):
            context = super(BookListView, self).get_context_data(**kwargs)
            form = SearchForm(load_all=True)
            context.update({'form': form})
            return context
    

    【讨论】:

    • 嗨@Pawan 感谢您的访问和回答。我在文件顶部添加了custom_login_required,然后将@method_decorator 放在get_context_data 上方,但出现错误wrap() takes at least 1 argument (0 given)。有什么线索吗?
    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 2014-04-30
    • 2021-09-17
    • 1970-01-01
    相关资源
    最近更新 更多