Method Call Behavior
Method calls are slightly more complex than the other lookup types. Here are some things to keep in mind:
-
If, during the method lookup, a method raises an exception, the exception will be propagated, unless the exception has an attribute silent_variable_failure whose value is True. If the exception does have asilent_variable_failure attribute, the variable will render as an empty string, for example:
-
A method call will only work if the method has no required arguments. Otherwise, the system will move to the next lookup type (list-index lookup).
-
Obviously, some methods have side effects, and it would be foolish at best, and possibly even a security hole, to allow the template system to access them.
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:
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.
上面是Django文档关于模版系统中方法调用的一部分内容。意思就是说,
在方法调用期间,如果被调用的方法发
起一个异常,如果此时这个异常
有silent_variable_failure这个属性,并且值为true,那么此时这个发生的异常不会传播,
并且在字符串中会被空字符串代替。如果属性值没有,那么就会
传播这个异常。在模板系统 中调用方法,这个方法必须是不接受任何参数的,否则这个方法不会被调用,
会按照点号引用的查找规则
进行下一项的查找。
另外,加入你现在有一个BlankAccount的类,这个类有一个account的对象,有一个delete的方法。
加入你在模板系统的变量里面
有{{account.delete}}这样的点号调用的话,会造成一些意想不到的问题。
模板中的account.delete和account对象调用delete不是一个意思,
这样的话就会出现了代码重复的情况。
所以Django会删除account这个对象,这样就造成 了不必要的麻烦。
给方法设置alters_data这个属性,在发生这种情况的时候,
程序不会调用任何方法,只是默默的退出。
要知道在Django模板系统中很多时候,
如果你用点号引用了一下不存在的变量或者方法,让系统深度查找不到的话,
那么他就会在那里用空字符串代替,虽然没有引发明显的异常,但是
这就已经代表 有错误了