我想做什么:
我正在查看用户是否来自“支持”组,然后才能查看该页面。如果不是,我想在响应页面中向用户显示正确的消息。 我有一个group_required装饰器应用于dispatch()视图方法,检查用户是否来自支持组。
我试过:
https://stackoverflow.com/a/29744943/2286762 但仍然得到ValueError。
我的代码
view.py
class ScheduledTestView(FormView):
'''
Provides an admin panel interface for creating scheduled tests.
Scheduled test will be created as active=False intially.
'''
serializer_class = TestShortSerializer
template_name = 'admin/scheduled_test.html'
form_class = ScheduledTestForm
@method_decorator(group_required(['support']))
def dispatch(self, request, *args, **kwargs):
return super(ScheduledTestView, self).dispatch(request, *args, **kwargs)
group_required函数
def group_required(group_names):
"""
group_name will be the list of group name
"""
def decorator(func):
@wraps(func, assigned=available_attrs(func))
def inner(request, *args, **kwargs):
user = request.user
if user.is_authenticated():
if (user.groups.filter(name__in=group_names) and user.is_staff) or user.is_superuser:
return func(request, *args, **kwargs)
return redirect_to_login('/admin/')
return inner
return decorator
错误
GET 请求网址:http://localhost:8000/admin/support/scheduled_test/
Django版本:1.8.4
异常类型:ValueError
例外值:
视图support.views.ScheduledTestView未返回HttpResponse对象。它改为返回None。例外地点:/home/kishan/.virtualenvs/kishan_pal/local/lib/python3.4/site-packages/django/core/handlers/base.py in get_response,第151行
答案 0 :(得分:1)
正如@Daniel Roseman在他的评论中提到的那样。如果用户未经过身份验证,那么inner
不会返回任何响应,而在这种情况下它应返回redirect_to_login('/admin/')
。
如此改变
def inner(request, *args, **kwargs):
user = request.user
if user.is_authenticated():
if (user.groups.filter(name__in=group_names) and user.is_staff) or user.is_superuser:
return func(request, *args, **kwargs)
return redirect_to_login('/admin/')
到
def inner(request, *args, **kwargs):
user = request.user
if user.is_authenticated():
if (user.groups.filter(name__in=group_names) and user.is_staff) or user.is_superuser:
return func(request, *args, **kwargs)
return redirect_to_login('/admin/')
应该解决问题。查看差异return redirect_to_login('/admin/')
位于if
区块之外。