【问题标题】:Django buggy template tag - 'NoneType' object has no attribute 'source'Django buggy 模板标签 - 'NoneType' 对象没有属性 'source'
【发布时间】:2009-12-10 08:55:48
【问题描述】:

想知道是什么原因造成的?让我难过一段时间了,一切都在控制台中运行时检查出来

作为旁注: 模板在其他地方使用相同的对象并显示值 - 模板中的对象也是下面控制台中加载的对象

错误

'NoneType' 对象没有属性 'source'

模板

{% form_transaction prop %}

控制台属性值

>>> prop = VacationHome.objects.get(pk=1)
>>> prop
<VacationHome: Samantha Dunn's vacation home at Close to Disney>
>>> prop.sell
0
>>> prop.rent
1
>>> count = 0
>>> string = ''
>>> type  = []
>>> num = 0
>>> for tr in TRANSACTION_MODEL:
...     if getattr(prop, tr, False):
...         type.append(count+1)
...         cur_count = count+1
...         string += '<li><label for="id_transaction_%s"><input type="checkbox" name="transaction" value="%s" id="id_transaction_%s" />%s</label></li>' % (count, cur_count, count, TRANSACTION_TITLE[count][1])
...         num += 1
...     count += 1
... 
>>> string
'<li><label for="id_transaction_1"><input type="checkbox" name="transaction" value="2" id="id_transaction_1" />Rental</label></li>'

定义

TRANSACTION_TITLE = (
    (1, 'Purchase'),
    (2, 'Rental'),
    (3, 'Exchange'),
)

TRANSACTION_MODEL = ['sell', 'rent', 'exchange']

模板标签

@register.tag
def prop_form_transaction(parser, token):
    try:
        tag_name, prop = token.split_contents()
        count = 0
        string = ''
        type  = []
        num = 0
        for tr in TRANSACTION_MODEL:
            if getattr(prop, tr, False):
                type.append(count+1)
                cur_count = count+1
                string += '<li><label for="id_transaction_%s"><input type="checkbox" name="transaction" value="%s" id="id_transaction_%s" />%s</label></li>' % (count, cur_count, count, TRANSACTION_TITLE[count][1])
                num += 1
            count += 1

        if num:
            if num > 1:
                return string
            else:
                return '<input type="hidden" name="transaction" value="'#+str(type[0])+'" />'
    except ValueError:
            raise template.TemplateSyntaxError, "%r tag requires exactly one argument" % token.contents.split()[0]

观看次数

def property_list_city(request, type, city):
city = str(city).replace('-', ' ')
if type == 'timeshare':
    timeshares = Timeshare.objects.filter(resort__city__icontains=city).filter(available__icontains=True)
    resorts = Resort.objects.filter(city__icontains=city)
    objects = chain(timeshares, resorts)
elif type == 'vacation_home':
    objects = VacationHome.objects.filter(city__icontains=city)
else:
    objects = False

context = {  #line 265
    'properties' : objects,
    'title' : city,
    'type' : type,
    }
return render_to_response('properties/properties_list.html', context_instance=RequestContext(request, context))

追溯

Environment:

Request Method: GET
Request URL: http://localhost:8000/properties/single/vacation_home/1/
Django Version: 1.1
Python Version: 2.6.4
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.humanize',
 'properties',
 'config',
 'sorl.thumbnail',
 'haystack',
 'south',
 'debug_toolbar']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware')


Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  92.                 response = callback(request, *callback_args, **callback_kwargs)
File "/home/alvin/workspace/timeshare/properties/views.py" in property_single
  272.     return property_single_context(request, type, property)
File "/home/alvin/workspace/timeshare/properties/views.py" in property_single_context
  265.     return render_to_response('properties/single.html', context, context_instance=RequestContext(request))
File "/usr/local/lib/python2.6/dist-packages/django/shortcuts/__init__.py" in render_to_response
  20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in render_to_string
  103.         t = get_template(template_name)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in get_template
  82.     template = get_template_from_string(source, origin, template_name)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in get_template_from_string
  90.     return Template(source, origin, name)
File "/usr/local/lib/python2.6/dist-packages/django_debug_toolbar-0.8.1.alpha-py2.6.egg/debug_toolbar/panels/template.py" in new_template_init
  28.     old_template_init(self, template_string, origin, name)
File "/usr/local/lib/python2.6/dist-packages/django/template/__init__.py" in __init__
  168.         self.nodelist = compile_string(template_string, origin)
File "/usr/local/lib/python2.6/dist-packages/django/template/__init__.py" in compile_string
  189.     return parser.parse()
File "/usr/local/lib/python2.6/dist-packages/django/template/__init__.py" in parse
  285.                     compiled_result = compile_func(self, token)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader_tags.py" in do_extends
  169.     nodelist = parser.parse()
File "/usr/local/lib/python2.6/dist-packages/django/template/__init__.py" in parse
  285.                     compiled_result = compile_func(self, token)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader_tags.py" in do_block
  147.     nodelist = parser.parse(('endblock', 'endblock %s' % block_name))
File "/usr/local/lib/python2.6/dist-packages/django/template/__init__.py" in parse
  289.                 self.extend_nodelist(nodelist, compiled_result, token)
File "/usr/local/lib/python2.6/dist-packages/django/template/debug.py" in extend_nodelist
  56.         node.source = token.source

Exception Type: AttributeError at /properties/single/vacation_home/1/
Exception Value: 'NoneType' object has no attribute 'source'

欢迎任何关于在哪里进行调试的想法 - 如果您碰巧知道导致错误的原因,请提前非常感谢

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    我遇到过几次这种情况,但一直都是一样的(至少对我而言)。如果模板标签函数没有返回任何内容,则会弹出此错误。

    class MyTag(template.Node):
      def __init__(self, name):
        self.name=name
      def render(self, context):
        context[self.name]='czarchaic'
        #return an empty string since we've only modified the context
        return ''
    @register.tag
    def my_tag(parser, token):
      bits=token.split_contents()
      if len(bits)==2:
        return MyTag(bits[1])
    
      #return an empty string if all test fail
      return ''
    

    编辑 查看您的代码,如果numif num: 处仍为 0,则检查此标记不会返回任何内容,从而导致此错误。

    【讨论】:

    • 在 num = 0 的情况下添加字符串输出得到错误:'str' 对象没有属性 'source' - 注释掉所有代码并留下返回 'test' 得到相同的错误...编程暂时围绕这件事,但让我烦恼的是我无法弄清楚......还有其他想法吗??
    • 哇,真是个笨蛋:)。可以发一下你的模板吗?再次查看您的代码,我很好奇tag_name, prop = token.split_contents()。第二位(prop)是字符串还是模板变量?我总是不得不通过template.Variable(prop).resolve(context) 运行模板变量。
    • 另外,您是否考虑过将这些位传递给template.Node 子类,从而使您能够访问上下文?这可能更适合作为 simple_tag
    【解决方案2】:

    您的源 views.py 的第 265 行(或 272)正在发送一个“NoneType”对象,更深层次的代码正试图从中获取“源”属性。换句话说,您正在向模板引擎发送一个空白 (NoneType) 对象,因此请查看这些行上方的代码,看看哪些对象在您发送出去时没有值。

    【讨论】:

    • 稍微修改了模板标签并添加了视图以供参考 - 第 265 行是定义模板上下文字典的地方 - 事情是当我注释掉模板标签时,一切正常......我挠头……
    • 关于 Oracle 通用存储过程问题...绝对没有问题可以通过谷歌搜索。 Google 可能会提供相互矛盾、不完整、过时、错误或错误的信息。 Jeff/Joel 曾多次表示,“googleable”问题很好,因此请让任何 cmets 对自己保持懒惰。他们不需要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多