-
-
Save gabeio/c5395c9af7747bcc5f22a106d095d7d6 to your computer and use it in GitHub Desktop.
Django template filters for getting various user-specific things off models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Some simple filters | |
* `user_can`, which filters an object taking a string | |
parameter, returning True or False depending on whether the current | |
user "can" do the action in the parameter. This is done by calling | |
`user_can_<action>` on the object. | |
Anonymous users always return `False`. | |
* `user_has`, which pulls the result of the `user_has_<feature>()`; | |
anonymous users get `False`. | |
* `user_property` pulls the result of `user_<property>()`; anonymous | |
users get `None`. | |
Relies on django-globals: https://github.com/svetlyak40wt/django-globals | |
Untested, based on internal code that didn't use django-globals. | |
""" | |
from django import template | |
from django_globals import globals | |
register = template.Library() | |
@register.filter | |
def user_can(value, arg): | |
"Is the current user allowed to perform the `arg` action on the `value` object?" | |
user = globals.user | |
if user.is_authenticated() and hasattr(value, "user_can_%s" % arg): | |
return getattr(value, "user_can_%s" % arg)(user) | |
else: | |
return False | |
@register.filter | |
def user_has(value, arg): | |
"Has the current user done the `arg` action on the `value` object?" | |
user = globals.user | |
if user.is_authenticated() and hasattr(value, "user_has_%s" % arg): | |
return getattr(value, "user_has_%s" % arg)(user) | |
else: | |
return False | |
@register.filter | |
def user_property(value, arg): | |
"A property user_{arg} on the object {value}." | |
user = globals.user | |
if user.is_authenticated() and hasattr(value, "user_%s" % arg): | |
return getattr(value, "user_%s" % arg)(user) | |
else: | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment