Skip to content

Instantly share code, notes, and snippets.

@jaylett
Created July 24, 2012 14:50
Show Gist options
  • Save jaylett/3170411 to your computer and use it in GitHub Desktop.
Save jaylett/3170411 to your computer and use it in GitHub Desktop.
Django template filters for getting various user-specific things off models
"""
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