【问题标题】:Django custom template tags: 'str' object has no attribute 'notification_set'Django 自定义模板标签:“str”对象没有属性“notification_set”
【发布时间】: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 我已经更新了问题。

标签: django django-templates


【解决方案1】:

知道了。改变了

{% unread request.user %}

{% unread user%}

它有效。 +10 让任何人解释这个错误。

【讨论】:

  • 您是否在设置中将django.core.context_processors.request 添加到TEMPLATE_CONTEXT_PROCESSORS 中?
  • @anhtran 不,我没有。在应用程序级模板中,我不必使用它,因为我猜上下文是由视图自动传递的,而在 base.html 的情况下,没有视图。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-05
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多