在基于django的项目中,我有一个自定义装饰器的视图:
@login_required
@user_is_project_maintainer
def edit(request, project_key):
...
和实际的自定义装饰器本身:
def user_is_project_maintainer(request):
def decorator(view_func, *args, **kwargs):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, project_key, *args, **kwargs):
project = get_object_or_404(Project, key=project_key)
if (project.maintainer_id != request.user.id) :
return HttpResponseRedirect(reverse('kifos.views.index', args=(project.key,)))
else :
view_func(request, *args, **kwargs)
return _wrapped_view
return decorator
这导致django本身('function' object has no attribute 'get'
)内部异常/django/core/handlers/base.py line 188
。无法弄清楚为什么会这样。有什么想法吗?
答案 0 :(得分:3)
这看起来像装饰器的一个过于复杂(可能已经破坏)的实现......相反如何:
def user_is_project_maintainer(view):
@wraps(view)
def _wrapped_view(request, project_key, *args, **kwargs):
project = get_object_or_404(Project, key=project_key)
if (project.maintainer_id != request.user.id) :
return HttpResponseRedirect(reverse('kifos.views.index', args=(project.key,)))
else :
view(request, project, *args, **kwargs)
return _wrapped_view
请注意,您的“编辑”视图现在自动将项目作为其第二个参数,因此您可以将其更改为:
def edit(request, project):
#can do stuff with project object in here