On 12/18/06, Crispin Bennett <[EMAIL PROTECTED]> wrote: > Is there a natural way in Django to write a template that can display > the details of objects of various types, where the types aren't > necessarily known in advance?
Even if the types aren't known in advance, it's possible to make some educated guesses; most classes will, for example, have a __str__ method which will allow them to intelligently print themselves as strings. If you know what types of objects are in the system (which is possible even if you don't know what types of objects you've been handed in a particular template instance), you can also look for common attributes and field names on them. If you know nothing at all about the objects and can't make any educated guesses, your best bet would be to write a template tag which can introspect the object and determine what attributes it has. For Python objects in general, the dir() function is the usual way to introspect like this -- see Chapter 4 of "Dive Into Python" [1] for details on how to use it. Django model instances provide additional hooks for introspection; each object has an attribute named '_meta' which contains information about the model class the object belongs to, including an attribute called 'fields' which lists all the fields of the model (so given an object 'o', 'o._meta.fields' will be the list of its fields). Your best bet would probably be to have your template tag begin by iterating over _meta.fields and looking at the names and types of the fields, then figuring out which, if any, of them to use for display. [1] http://diveintopython.org/power_of_introspection/index.html -- "May the forces of evil become confused on the way to your house." -- George Carlin --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---