Here is a short guide on using custom decorators in Django as I did not find one with a good explanation. A decorator is essentially a function that is wrapped around the original. They are defined in TWO slightly different ways depending on whether parameters are used. Example:
in views.py
1 2 3 4 5 6 7 8 9 | #no parameter @something_required def my_view(request, item_id): return ... #with parameter @something_required_with('parameter') def my_view2(request, item_id): return... |
If there are parameters, the view function will be wrapped TWICE.
in decorators.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | from functools import wraps from django.http import HttpResponse, HttpResponseRedirect from django.utils.decorators import available_attrs #no parameter def something_required(view_func): @wraps(view_func, assigned=available_attr(view_func)) def wrapper(request, *args, **kwargs) item_id = kw.get('item_id', None) if item_id: return view_func(request, *args, **kwargs) else: return HttpResponseRedirect('home') return wrapper #with parameter def something_required_with(parameter): def decorator(view_func): #second wrapper gets view_func @wraps(view_func, assigned=available_attr(view_func)) def wrapper(request, *args, **kwargs) item_id = kw.get('item_id', None) if item_id == parameter: return view_func(request, *args, **kwargs) else: return HttpResponseRedirect('home') return wrapper return decorator |