Login

Passing values to a method from a template

Author:
miracle2k
Posted:
March 16, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

A simple trick to let a function be called with exactly ONE argument from a Django template, by passing it via an attribute. Example:

class SearchResult(object):
    @template_callable
    def highlighted(self, field):
        return self._xappy_result.highlight(field)

result = SearchResult()
result.highlighted.title

{{ result.highlighted.title }}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def template_callable(func):   
    class GetAttrCaller(object):
        def __init__(self, instance):
            self.instance = instance
        def __getattr__(self, name):
            return func(self.instance, name)
        # Would cause Django to think this is a method, even through templates
        #def __call__(self, *args, **kwargs):
        #    return func(self, *args, **kwargs)
    class TemplateCallableDescriptor(object):
        def __get__(self, instance, klass):
            return GetAttrCaller(instance)
    return TemplateCallableDescriptor()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 6 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 6 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 1 month ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 1 month ago
  5. Help text hyperlinks by sa2812 1 year, 2 months ago

Comments

gvkreddyvamsi (on April 18, 2008):

HI,

Iam new to python and django.

Here i need to enable radio buttons on home screen depending on data stored in model database. How we can do this to get data in database and enabling radio buttons on same screen?

For example i have to choose role which is not filled already.

Plz help me.

my mail [email protected]

Thanks in advance by vamsi

#

Please login first before commenting.