Hi Fabio, > I need to pass a model to my template and then access its > attributes. Some of them start with an underscore, which turns out to > be a problem for the template mechanism. > > I think there are two major roads to solve this: > > - write new template tags > - add a new method to each of my models (lot of new code to write?) > > Are there any other alternatives? Which is the best bet? Could you > kindly point me out a few urls where I can study those topics?
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 --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---