On 12/19/06, James Bennett <[EMAIL PROTECTED]> wrote: > > 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.
This is roughly my situation -- ie. I know what are the possible objects, just not what particular objects I'll get on a given occasion. > > 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. Thanks. Though new to Python, I've got an overview of its introspection facilities, but I haven't looked into the _meta stuff yet, so I'll do that. I was primarily wondering whether there's a 'natural' Django idiom or pattern for doing this kind of thing. My first crude attempt is to have a method in the model that provides a predictable template name for the object. Then in my main template I include the relevant template for the object. It works, but doesn't quite feel right. Perhaps I should be using custom tags, or maybe I could do something more dynamic, removing the need to code specifically for each model altogether? --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---