【发布时间】:2014-06-20 07:59:51
【问题描述】:
在定义一个作用于顶层 base.html(而不是应用程序级基础)的自定义模板标记时,我遇到了一个在 shell 上执行得很好的查询的问题。
例如,
from django.contrib.auth.models import User
u = User.objects.get(pk=3)
u.notification_set.filter(viewed=False).count() # returns 1 as expected
但是,在模板标签中,这给了我一个奇怪的错误
AttributeError at /mynotes/
'str' object has no attribute 'notification_set'
. 是我的 manage.py,这里是自定义模板标签:
./app/templatetags/mytags.py
from django import template
register = template.Library()
@register.simple_tag(name="unread")
def get_unread(user):
return user.notification_set.filter(viewed=False).count()
./templates/base.html
{% load mytags %}
...
{% unread request.user%}
编辑:./app/models.py
class Notification(models.Model):
message = models.TextField()
notification_for_user = models.ForeignKey(User)
viewed = models.BooleanField(default=False)
...
【问题讨论】:
-
你能显示
models.py部分吗? -
@anhtran 我已经更新了问题。