20 March, 2010

notes from django book--ch4

Dot lookups can be summarized like this: when the template system encounters a dot in a variable name, it tries the following lookups, in this order:
  • Dictionary lookup (e.g., foo["bar"])

  • Attribute lookup (e.g., foo.bar)

  • Method call (e.g., foo.bar())

  • List-index lookup (e.g., foo[2])

The system uses the first lookup type that works. It’s short-circuit logic.
Say, for instance, you have a BankAccount object that has a delete() method. If a template includes something like {{ account.delete }}, where account is a BankAccount object, the object would be deleted when the template is rendered!

To prevent this, set the function attribute alters_data on the method:

def delete(self):
    # Delete the account
delete.alters_data = True


The template system won’t execute any method marked in this way. Continuing the above example, if a template includes {{ account.delete }} and the delete() method has the alters_data=True, then thedelete() method will not be executed when the template is rendered. Instead, it will fail silently
.

No comments: