【问题标题】:How can I raise exception in model while rendering the template?渲染模板时如何在模型中引发异常?
【发布时间】:2023-10-19 03:04:01
【问题描述】:

我在模型类中有一些自定义函数来处理一些数据,然后将自定义属性添加到模型中。问题是,如果在生成模板时有任何异常,我不知道如何引发异常(错误似乎只是无声的,因此它将进一步处理模板但给出 NO ERROR ) 在视图中

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 以便模板处理立即停止,或者给渲染函数一些异常? 谢谢

【问题讨论】:

  • 你可以使用somedict.get('b', None)而不是引发错误吗?
  • 字典的使用就是一个例子。异常可以是一切,我正在从远程服务器获取状态属性,如果连接有问题,我不能让它知道。
  • 您是使用任何特定的库来处理远程请求还是自定义解决方案?

标签: django django-models


【解决方案1】:

根据docs

如果变量在调用时引发异常,则会传播该异常,除非该异常有一个值为Trueattribute silent_variable_failure。如果异常确实具有值为Truesilent_variable_failure 属性,则该变量将呈现为空字符串。

还有例子:

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

【讨论】:

  • 感谢您的指出。 - If the variable raises an exception when called, the exception will be propagated, unless the exception has an attribute silent_variable_failure whose value is True.
【解决方案2】:

您可以将TEMPLATE_DEBUG 设置为True

【讨论】:

    【解决方案3】:

    我遇到了与您类似的问题。 但让我感到困惑的问题是,为什么当我 没抓到。

    好像是在接触模型实例的时候才发生的(eg.getattr(model, not_exists_attribute))。

    【讨论】: