Created
May 24, 2012 13:43
-
-
Save mativs/2781616 to your computer and use it in GitHub Desktop.
Template tag filters to call an instance method with 'user' parameter
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
from django import template | |
register = template.Library() | |
@register.filter | |
def with_user(instance, user): | |
""" | |
stores the user in the instance attribute '_onuser' wether exists or not. | |
""" | |
setattr(instance, "_onuser", user) | |
return instance | |
@register.filter | |
def call_method(instance, method): | |
""" | |
calls the instance method 'method' passing the argument 'user' with the instance | |
variable '_onuser'. | |
Usage: {{ instance|with_user:user|call_method:"my_method_name" }} | |
""" | |
method = getattr(instance, method) | |
if hasattr(instance, "_onuser"): | |
try: | |
to_return = method(user=instance._onuser) | |
except: | |
to_return = method() | |
return to_return | |
return method() |
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
from django.test import TestCase | |
from django.template import Template, Context | |
from django.contrib.auth.models import User | |
class OnUserToTest(): | |
def usernames(self, user=None): | |
basic = ['basico'] | |
if user: | |
basic.append(user.username) | |
return basic | |
class OnUserTestCase(TestCase): | |
def test_with_user_method(self): | |
u = User(username='prueba') | |
c = Context({ 'test': OnUserToTest(), 'user':u}) | |
t = Template ("{% load users_extras %}{% for username in test|with_user:user|call_method:'usernames' %}{{username}}{% endfor %}") | |
r = t.render(c) | |
self.assertEquals(r, 'basicoprueba' ) | |
def test_no_parameters(self): | |
t = Template ("{% load users_extras %}{% for username in test.usernames %}{{username}}{% endfor %}") | |
u = User(username='prueba') | |
c = Context({ 'test': OnUserToTest(), 'user':u}) | |
r = t.render(c) | |
self.assertEquals(r, 'basico' ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment