如何在渲染模板时在模型中引发异常?

时间:2013-09-16 10:40:16

标签: django django-models

我在模型类中有一些自定义函数处理一些数据,然后将自定义属性添加到模型中。事情是,我不知道如果生成模板时有什么可能引发异常(错误似乎只是沉默,所以它会进一步处理模板但是没有错误) 在视图中

test.objects.all()
render_to_string('template.html', {'test': test})

在模板中

{{ entry.state }}

在模型中:

@property
def state(self):
    somedict = {'a': 111}
    try:
       print somedict['b']
    except Exception as e:
       FATAL_ERROR

我应该将什么放在fatal_error的位置,以便模板处理应该立即停止,或者给渲染函数一些例外? 感谢

3 个答案:

答案 0 :(得分:0)

您可以将TEMPLATE_DEBUG设置为True

答案 1 :(得分:0)

根据docs

  

如果变量在调用时引发异常,则会传播异常,除非异常的attribute silent_variable_failure值为True。如果异常的silent_variable_failure属性值为True,则该变量将呈现为空字符串。

示例:

t = Template("My name is {{ person.first_name }}.")
class PersonClass3:
    def first_name(self):
        raise AssertionError("foo")
p = PersonClass3()
t.render(Context({"person": p}))
#Error raised


class SilentAssertionError(Exception):
    silent_variable_failure = True

class PersonClass4:
    def first_name(self):
        raise SilentAssertionError
p = PersonClass4()
t.render(Context({"person": p}))
"My name is ."
#No error raised

答案 2 :(得分:0)

我遇到了与你类似的问题。 但让我感到困惑的问题是,为什么异常根本不会引起我的注意 没有抓住它。

它似乎恰好在触摸模型实例时发生(例如getattr(model,not_exists_attribute))。

相关问题