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

时间:2012-03-19 19:53:14

标签: python django django-templates

编辑:我经过大量时间调试了回溯。看看答案的结尾。

我编写了一个自定义模板标记,用于检查网站上的特定组是否由用户添加书签,并根据该标记向html添加特定内容。

我写的tempplate标签如下。

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部分是

{% if user.is_authenticated %}

{% if_bookmarked user pageuri %}

<p>you bookmared this</p>

{% else %}

<form method="post" {{bookmarkformaction}} >

details:<textarea rows="2" cols="20"name='bookmarkdetails'> </textarea> 
name:<input type="text" id="id_bookmarkname" name='bookmarkname' value="" />
<input type="submit" name="add-bookmark" value="Add Bookmark" />

</form>

{% endif_bookmarked %}

{% else %}
<a href="/accounts/login/">login</a>
<a href="/accounts/register/">register</a>
{% endif %}

我知道回溯中的节点对象是“无”,但我很困惑如何解决这个问题。我在俯瞰什么?

如果信息不充分或问题不明确,请告诉我。我会根据需要修改它。

回溯:

    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'

编辑:发生此问题是因为do_if_bookmarked方法在某些情况下没有返回任何对象。确保你有一些beign返回的对象。

1 个答案:

答案 0 :(得分:2)

也许尝试在这里使用简单的{%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 %}

恕我直言,阅读和调试更加清晰