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
- Serializer factory with Django Rest Framework by julio 5 months, 3 weeks ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 6 months, 1 week ago
- Help text hyperlinks by sa2812 7 months, 1 week ago
- Stuff by NixonDash 9 months, 2 weeks ago
- Add custom fields to the built-in Group model by jmoppel 11 months, 2 weeks ago