数据库只有 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')