V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
pc10201
V2EX  ›  Python

django 的 VariableDoesNotExist 的异常

  •  
  •   pc10201 · 2016-02-14 13:07:53 +08:00 · 4127 次点击
    这是一个创建于 2992 天前的主题,其中的信息可能已经有所发展或是发生改变。
    python 2.7.11 and django 1.9
    I run the code in "python manage.py shell"

    Django 1.9
    In[2]: import django
    In[3]: from django.template import Template, Context
    In[4]: t = Template("{% if x and x.strip %}OK{% else %}Empty{% endif %}")
    In[5]: t.render(Context({}))
    2015-12-17 14:13:43,443 [MainThread:3140] [django.template:923] [base:_resolve_lookup] [DEBUG]- Exception while resolving variable 'x' in template 'unknown'.
    Traceback (most recent call last):
    File "D:\Python27\lib\site-packages\django\template\base.py", line 901, in _resolve_lookup
    (bit, current)) # missing attribute
    VariableDoesNotExist: Failed lookup for key [x] in u"[{'False': False, 'None': None, 'True': True}, {}]"
    Out[5]: u'Empty'

    I use "if" in template,but it has excepiton.

    众位群友,有知道怎么解决的吗?
    3 条回复    2016-02-14 14:31:07 +08:00
    jimmyye
        1
    jimmyye  
       2016-02-14 13:19:21 +08:00
    >Exception while resolving variable 'x' in template 'unknown'.
    你要在`Context`中传入`x`
    pc10201
        2
    pc10201  
    OP
       2016-02-14 13:26:08 +08:00
    @jimmyye 我想直接在模板中判断,在 jinjia2 中就可以这样直接使用,在 django 中就不行
    jimmyye
        3
    jimmyye  
       2016-02-14 14:31:07 +08:00
    @pc10201 哦,刚才没看清楚,确实这在模板中是不会抛出异常的,就算不判断,也只会静默处理。

    https://github.com/tomchristie/django-rest-framework/issues/3736
    这里有讨论到 django 1.9 的一些变化:
    https://docs.djangoproject.com/en/1.9/topics/logging/#django-template

    是因为 logger 的一些变化导致了原来静默的异常现在被输出了。
    > 2015-12-17 14:13:43,443 [MainThread:3140] [django.template:923] [base:_resolve_lookup] [DEBUG]
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   971 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 21:16 · PVG 05:16 · LAX 14:16 · JFK 17:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.