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
garygay
V2EX  ›  Python

请教使用 Django 时,提示 local variable 'xxx' referenced before assignment 的问题

  •  1
     
  •   garygay · 2017-05-26 15:21:25 +08:00 · 3873 次点击
    这是一个创建于 2498 天前的主题,其中的信息可能已经有所发展或是发生改变。
    数据库只有 4 条数据,localhost/mysite/detail/4,访问的是第四条信息,当输入 detail/5 的时候报错,但是设计中应该是提示没有该商品。我在 stackoverflow 上看到有类似的问题,和 POST 有关?
    https://stackoverflow.com/questions/3881601/require-help-in-django-local-variable-form-referenced-before-assignment

    下面是代码,如果有描述不清楚的,我会随时改,谢谢大家。

    [ views.py ]

    def detail(request, id):
    try:
    product = models.Product.objects.get(id=id)
    images = models.PPhoto.objects.filter(product=product)
    except:
    pass
    #为什么下面的会报错
    return render(request, 'mysite/detail.html', {'product':product, 'images':images})
    #改成下面这个就没问题
    template = get_template('mysite/detail.html')
    html = template.render(locals())
    return HttpResponse(html)

    [ detail.html ]

    {% if product %}
    <table>
    <tr><td align="center"><h3>{{ product.nickname }}</h3></td></tr>
    <tr><td align="center">{{ product.description }}</td></tr>
    <tr><td align="center">{{ product.year }}年出产</td></tr>
    <tr><td align="center">{{ product.price }}元</td></tr>
    {% else %}
    <h2>找不到该手机</h2>
    {% endif %}

    [ index.html ]

    <td><a href="{% url 'detail-url' p.id %}">{{ p.nickname }}</a></td>

    [ url.py ]

    url(r'^detail/(\d+)$', views.detail, name='detail-url')
    jimmyye
        1
    jimmyye  
       2017-05-26 16:02:59 +08:00
    因为异常导致赋值没有进行,在 except 里给它们赋值 None 就行了
    111111111111
        2
    111111111111  
       2017-05-26 19:28:14 +08:00 via Android
    product = 这一行异常,导致下一行没有执行
    在 try 前或者 except 给 images 设置初始值即可
    另外 filter 查不到数据不会异常 可以放到 except 外面,这样也可以解决 lz 的问题
    garygay
        3
    garygay  
    OP
       2017-05-27 10:48:35 +08:00
    @jimmyye
    @111111111111 谢谢你们
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5489 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 09:01 · PVG 17:01 · LAX 02:01 · JFK 05:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.