How to access underscore starting attributes in templates | Fabio Natali | 9/3/08 9:28 AM | Hi all of you. I need to pass a model to my template and then access its I think there are two major roads to solve this: - write new template tags Are there any other alternatives? Which is the best bet? Could you Thank you very much, -- |
Re: How to access underscore starting attributes in templates | Rajesh Dhawan | 9/3/08 12:11 PM | Hi Fabio,
The best practice in Django (and in Python too) is not to use underscore-prefixed attributes outside of the class/module they are defined in. Such attributes are typically meant to signify internally used names that can change in future. They are similar to private or non-public variables/methods in other languages. See: http://www.python.org/dev/peps/pep-0008/ If you agree with this, your best bet is to revise your design so that attributes that are publically used in templates, views, etc. are named without the leading underscores. This will make your code much more maintainable both by you and others. Alternatively, create a method/property (your second solution above) to access each one of them publically. If you still want to go ahead with the template tag approach for a short-term time saving (and long-term pain :), you can write one template tag to give you back all such attributes on any of your models. The code could be along these lines: @register.simple_tag def get_private_attribute(model_instance, attrib_name): return getattr(model_instance, attrib_name, '') You would use it like this in a template: {% get_private_attribute model_object "_my_private_var_name" %} -Rajesh D |
Re: How to access underscore starting attributes in templates | Fabio Natali | 9/3/08 2:39 PM | Dear Rajesh, thanks for your precious help. Rajesh Dhawan scrisse:
> Alternatively, create a method/property (your second solution above)
I added a couple of methods to my models, so to access to the TemplateSyntaxError at / I put some excerpts in http://dpaste.com/75743/. Can anybody see Thanks. > -Rajesh D All the best, -- |
Re: How to access underscore starting attributes in templates | bruno desthuilliers | 9/3/08 2:44 PM | On 3 sep, 23:39, Fabio Natali <nat...@poisson.phc.unipi.it> wrote:
(snip) > I added a couple of methods to my models, so to access to the> I put some excerpts inhttp://dpaste.com/75743/. Can anybody see > what's missing/wrong? Yeps : you're calling an instancemethod on a class. For what you're trying to do, you need classmethods, ie: @classmethod def verbosename(cls): return unicode(cls._meta.verbose_name) @classmethod def verbosenameplural(cls): return unicode(cls._meta.verbose_name_plural) HTH |
Re: How to access underscore starting attributes in templates | Fabio Natali | 9/3/08 11:26 PM | Dear Bruno, thank you very much for your help!! bruno desthuilliers wrote:
It did the trick! Now everything's fine. And I advanced a small step See ya, -- |