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 ...
else:
... 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:
@permission
def user_owns_comment(request, comment_id):
return request.user == Comment(id=comment_id)
@login_required
@user_owns_comment
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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Cool snippet. Thanks!
#
Please login first before commenting.