尝试循环遍历模板中的 SimpleLazyObject 会引发错误
Trying to loop over SimpleLazyObject in template throws an error
我已经创建了一个模板上下文处理器来查询每个页面上的数据库以获取任何全局通知。我正在使用 SimpleLazyObject
将结果提供给模板,这是必要的,因为所讨论的函数最终取决于来自不同模板上下文处理器的另一个 SimpleLazyObject
。这是函数:
def company_notifications(request):
def get_notifications():
from app.services.companies import CompanyNotificationService
notifications = CompanyNotificationService().company_notifications(request.profile.company)
return notifications
return {
'notifications': SimpleLazyObject(get_notifications),
}
当我尝试循环遍历模板中的 notifications
变量(即 for notification in notifications
)时,出现以下错误:
TypeError at /staff/notifications object of type 'SimpleLazyObject'
has no len()
如果我只是尝试使用 {{ notifications }}
将变量打印到模板,我会得到我期望的结果:
[<CompanyNotification: 57>, <CompanyNotification: 55>, <CompanyNotification: 59>]
但是如果我尝试打印其中一个对象的 属性,即 {{ notifications[0].headline }}
,我会收到一个新错误:
TemplateSyntaxError at /staff/notifications
Could not parse the remainder: '[0].headline' from 'notifications[0].headline'
如何在我的模板中访问这个变量?
@Alasdair 的评论是正确的。这是 Django < 1.7 中的错误。我的 hacky 解决方案是继承 SimpleLazyObject:
class SimpleLazyObjectFix(SimpleLazyObject):
def __len__(self, *args, **kwargs):
return 1
我已经创建了一个模板上下文处理器来查询每个页面上的数据库以获取任何全局通知。我正在使用 SimpleLazyObject
将结果提供给模板,这是必要的,因为所讨论的函数最终取决于来自不同模板上下文处理器的另一个 SimpleLazyObject
。这是函数:
def company_notifications(request):
def get_notifications():
from app.services.companies import CompanyNotificationService
notifications = CompanyNotificationService().company_notifications(request.profile.company)
return notifications
return {
'notifications': SimpleLazyObject(get_notifications),
}
当我尝试循环遍历模板中的 notifications
变量(即 for notification in notifications
)时,出现以下错误:
TypeError at /staff/notifications object of type 'SimpleLazyObject' has no len()
如果我只是尝试使用 {{ notifications }}
将变量打印到模板,我会得到我期望的结果:
[<CompanyNotification: 57>, <CompanyNotification: 55>, <CompanyNotification: 59>]
但是如果我尝试打印其中一个对象的 属性,即 {{ notifications[0].headline }}
,我会收到一个新错误:
TemplateSyntaxError at /staff/notifications Could not parse the remainder: '[0].headline' from 'notifications[0].headline'
如何在我的模板中访问这个变量?
@Alasdair 的评论是正确的。这是 Django < 1.7 中的错误。我的 hacky 解决方案是继承 SimpleLazyObject:
class SimpleLazyObjectFix(SimpleLazyObject):
def __len__(self, *args, **kwargs):
return 1