在django,我们可以这样做:
views.py :
def A(request):
context = {test : 'test'}
return render_to_response('index.html', context , context_instance = RequestContext(request))
def B(request):
context = {}
return render_to_response('index.html', context , context_instance = RequestContext(request))
index.html:
{% if test %}
{{ test }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
让我们的模板渲染没有错误,即使我使用method B,其中变量'test'不存在,但我仍然可以把它放在模板中.
我想在控制器中用pylons + mako做同样的事情:
foo.py
def A(self):
c.test = 'test'
return render('index.html')
def B(self):
return render('index.html')
index.html :
% if c.test:
${'c.test'}
% endif
Run Code Online (Sandbox Code Playgroud)
在Django中,我可以做到这一点,但在Pylons中,我收到一个错误,无论如何检查是否'c.test'存在?
错误:AttributeError:'ContextObj'对象没有属性'test'
假设我有:
class Album(models.Model):
photos = models.ManyToManyField('myapp.Photo')
photo_count = models.IntegerField(default = 0)
class Photo(models.Model):
photo = models.ImageField(upload_to = 'blahblah')
Run Code Online (Sandbox Code Playgroud)
我想要的是,每次调用.add()方法时,都会增加photo_counton Album类,所以我想覆盖.add()方法.问题是,我无法导入.add()该类,因为它在方法内部,所以它就像def->class->def.那么无论如何要覆盖.add()?或者有更好的方法来做到这一点?