Reputation: 719
I have a simple view function, and a decorator for it, and I want to use a parameter passed to view in the decorator. I've googled around but haven't found any example for this, and I'm still not sure it this possible at all, and if so - how to do this?
View with decorator appended:
@user_is_project_maintainer
def edit(request, project_id_key):
decorator itself:
def user_is_project_maintainer():
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if (project_id_key.isdigit()) :
project = get_object_or_404(Project, pk=project_id_key)
else :
project = get_object_or_404(Project, key=project_id_key)
if (project.maintainer_id != request.user.id) :
return HttpResponseRedirect(reverse('core.views.index', args=(project.key,)))
else :
view_func(request, *args, **kwargs)
return _wrapped_view
return decorator
I've copied one of default django view decorators and amended it for my needs, I'm sure I've done it wrongly but it's not the case. The main thing I can't figure out - how to get my hands on the project_id_key
var inside the decorator?
Upvotes: 0
Views: 313
Reputation: 1298
In _wrapped_view you have access to args and kwargs. So project_id_key should be available as args[0]
.
But I would rather do it in more explicit way:
def _wrapped_view(request, project_id_key, *args, **kwargs):
Upvotes: 4
Reputation: 239250
It'll be in the kwargs
in _wrapped_view
, i.e. project_id_key = kwargs['project_id_key']
.
Upvotes: 3