呈现自定义模板标记时,“NoneType”对象没有属性“source”错误

2024-10-01 07:30:34 发布

您现在位置:Python中文网/ 问答频道 /正文

在编辑:我调试过了经过很长时间的回溯。请看问题的结尾以寻找答案。在

我编写了一个自定义模板标记,用于检查用户是否为网站上的特定组添加了书签,并基于此将特定内容添加到html中。在

我写的template标签如下。在

def do_if_bookmarked(parser, token):
    bits = token.contents.split()
    if len(bits) != 3:
        raise template.TemplateSyntaxError("%s tag takes two arguments" % bits[0])

    nodelist_true = parser.parse(('else', 'endif_bookmarked'))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse(('endif_bookmarked',))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()
    return IfBookmarkedNode(bits[1], bits[2], nodelist_true, nodelist_false)

class IfBookmarkedNode(template.Node):
    def __init__(self, user, pageuri, nodelist_true, nodelist_false):
        self.nodelist_true = nodelist_true
        self.nodelist_false = nodelist_false
        self.user = template.Variable(user)
        self.pageuri = template.Variable(pageuri)

    def render(self, context):
        try:
            user = self.user.resolve(context)
            pageuri = self.pageuri.resolve(context)
        except template.VariableDoesNotExist:
            return ' '

        if BookmarkTag.objects.filter(user__pk=user.id,
                                   pageuri=pageuri):
            return self.nodelist_true.render(context)
        else:
            return self.nodelist_false.render(context)

register = template.Library()
register.tag('if_bookmarked', do_if_bookmarked)

html部分是

^{pr2}$

我知道从回溯来看node对象是'None',但是对于如何解决这个问题我感到困惑。我忽略了什么?在

请让我知道,如果信息是不可取的或如果问题不清楚。我会按要求修改。在

回溯:

    Environment:


    Request Method: GET
    Request URL: http://localhost:8000/posttags/page/-EE-Btech/

    Django Version: 1.3.1
    Python Version: 2.7.2
    Installed Applications:
    ['registration_defaults',
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.sites',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'registration',
     'debug_toolbar',
     'postpots']
    Installed Middleware:
    ('debug_toolbar.middleware.DebugToolbarMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware')


    Traceback:

        File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
          111.                         response = callback(request, *callback_args, **callback_kwargs)
        File "/home/Qalqi/Projects/Python/Django/djangopath/postpots/views.py" in page
          42.                               context_instance=RequestContext(request))
        File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django

/shortcuts/__init__.py" in render_to_response
      20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
      181.         t = get_template(template_name)
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/template/loader.py" in get_template
      157.     template, origin = find_template(template_name)
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/template/loader.py" in find_template
      134.             source, display_name = loader(name, dirs)
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/template/loader.py" in __call__
      42.         return self.load_template(template_name, template_dirs)
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/template/loader.py" in load_template
      48.             template = get_template_from_string(source, origin, template_name)
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/template/loader.py" in get_template_from_string
      168.     return Template(source, origin, name)
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/debug_toolbar/panels/template.py" in new_template_init
      37.     old_template_init(self, template_string, origin, name)
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/template/base.py" in __init__
      108.         self.nodelist = compile_string(template_string, origin)
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/template/base.py" in compile_string
      136.     return parser.parse()
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/template/base.py" in parse
      239.                     compiled_result = compile_func(self, token)
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/template/defaulttags.py" in do_if
      922.     nodelist_true = parser.parse(('else', 'endif'))
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/template/base.py" in parse
      243.                 self.extend_nodelist(nodelist, compiled_result, token)
    File "/home/Qalqi/.virtualenvs/sandmaze/local/lib/python2.7/site-packages/django/template/debug.py" in extend_nodelist
      58.         node.source = token.source

    Exception Type: AttributeError at /posttags/page/-EE-Btech/
    Exception Value: 'NoneType' object has no attribute 'source'

EDit:发生此问题的原因是do\u if\u bookmarked方法在某些情况下没有返回任何对象。确保你有一些被返回的对象。在


Tags: djangoinpyselfhomelibpackageslocal
1条回答
网友
1楼 · 发布于 2024-10-01 07:30:34

也许可以尝试在这里使用简单的{%if%}+模板过滤器?这样您就可以避免构造复杂的标记代码,下面是这样的:

@register.filter
def bookmarked(user, page_uri):
   return BookmarkTag.objects.filter(user__pk=user.id, pageuri=pageuri).count()


{% if user|bookmarked:page_uri %}{% else %}{% endif %}

我的阅读和调试更加清晰

相关问题 更多 >