- July 4, 2008
- view decorator permission
- 1 (after 1 ratings)
This is a simple helper to make custom permission decorators for Django views.
Perhaps you have an edit_comment view which you want to make sure current user is the owner of:
def edit_comment(request, comment_id):
if request.user == Comment(id=comment_id).user:
... do authorized things ...
... do unauthorized things ...
In this view, you might do a quick check
if request.user == Comment(id=comment_id).user, however you now need to duplicate this code all over the place whenever you want to check if a comment is owned by the current user.
Instead, you can use the built in login_required decorator, and your own decorator to do the test:
def user_owns_comment(request, comment_id):
return request.user == Comment(id=comment_id)
def edit(request, comment_id):
... ... ...
The "tester" function will post a message using the messages module built into Django, and redirect the user to the root. It allows access and executes the view if the tester function returns anything that evaluates to True.
Your permission tester should either strictly specify the same arguments as the view, or take additional args, and *kwargs to prevent syntax errors on extra arguments being passed along.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
from django.http import HttpResponseRedirect from functools import wraps def permission(permission_tester): @wraps(permission_tester) def view_decorator(view_function): @wraps(view_decorator) def decorated_view(request, *args, **kwargs): if permission_tester(request, *args, **kwargs): view_result = view_function(request, *args, **kwargs) else: try: request.user.message_set.create(message="Sorry, you don't have the necessary permissions to view that page.") except: pass view_result = HttpResponseRedirect("/") return view_result return decorated_view return view_decorator
More like this
- FieldLevelPermissionsAdmin by buriy 8 years, 5 months ago
- JSON decorator for views handling ajax requests by anilshanbhag 3 years, 1 month ago
- Allow separation of GET and POST implementations by agore 3 years, 8 months ago
- dropbox integration by ivarne 3 years, 11 months ago
- Cache view by user (and anonymous) by rafaelsdm 4 years, 5 months ago