custom view decorators
Date: May 2nd 2016
Last updated: May 2nd 2016
Decorators can provide a short cut method for adding extra content to a function. Django has some builtin decorators like the login_required decorator. For more information on decorators see oop/decorators pt1, oop/decorators pt2, and oop/decorators pt3.
useful resources
- http://stackoverflow.com/questions/11872560/how-to-pass-django-request-object-in-user-passes-test-decorator-callable-functio
- https://github.com/mzupan/django-decorators/blob/master/auth.py
- http://francoisgaudin.com/2013/08/22/decorators-in-django/
- http://stackoverflow.com/questions/9397584/why-is-my-django-view-decorator-not-getting-the-request-passed-to-it
views.py
In this example, only a user (via request) can implement the editfins method if they are also associated with the surfer who added the fins in the first place.
from functools import wraps
def surfer_matches_user(test_func):
@wraps(test_func)
def _wrapped_view(request,surfer_id):
if int(request.user.surfer.id) == int(surfer_id):
return test_func(request, surfer_id)
else:
return redirect('/{}/'.format(request.user.surfer.id))
return _wrapped_view
@login_required
@surfer_matches_user
def editfins(request, surfer_id, fins_id):
fins = get_object_or_404(Fin, pk=fins_id)
form = FinsForm(request.POST or None, instance=fins)
if form.is_valid():
form.save()
return redirect('/{}/'.format(surfer_id))
return render(request, 'surferprofile/updatefins.html',
{'fins': fins, 'form': form})