项目不会显示

时间:2012-04-28 07:26:05

标签: python django

urls.py

from item.models import ItemCategory, Item
from django.conf.urls.defaults import patterns, include, url

urlpatterns = patterns('order.views',
    url(r'^$', 'index'),
    url(r'category/$', 'category'),
    url(r'(?P<cat_id>\d+)/$', 'item'),
)

views.py

from django.http import HttpResponse
from item.models import ItemCategory, Item
from django.shortcuts import render_to_response, get_object_or_404

def item(request, cat_id):
    item_list = get_object_or_404(ItemCategory, pk=cat_id)
    return render_to_response('order/item.html', {'item_list':item_list})

item.html

{% if item_list %}
    <h3>{{ item_list.name }}</h3>
    <ul>
        {% for item in item_list.choice_set.all %}
            <li>{{ item.id }} - {{ item.item }}</li>
        {% endfor %}
    </ul>
{% endif %}



根据上述代码,它应显示:

类别1

- item 1
- item 2

但它只显示如下:

类别1

它不显示项目

这可能有什么不妥?

1 个答案:

答案 0 :(得分:0)

您是否从教程中复制了此代码?连接模型是否故意称为choice_set?如果您的Item模型有ForeignKey(ItemCategory),那么它应为item_set。但这只是一个纯粹的猜测。

我会在视图中返回一个调试行,然后检查该项是否在choice_set中有这些选项。如果你有一个调试器并且可以看到真正发生的事情而不是阅读代码和猜测,那么问题就很难解决。

def item(request, cat_id):
    item_list = get_object_or_404(ItemCategory, pk=cat_id)
    import pdb; pdb.set_trace()
    return render_to_response('order/item.html', {'item_list':item_list})

或更好的IPDB(您必须使用easy_install或pip安装它)

def item(request, cat_id):
    item_list = get_object_or_404(ItemCategory, pk=cat_id)
    import ipdb; ipdb.set_trace()
    return render_to_response('order/item.html', {'item_list':item_list})

在调试器中,编写变量并检查它是否符合您的期望:

>>> item_list
[some output]
>>> item_list.choice_set.all()
[some output]

(Offtopic)有django_annoying应用程序和有用的快捷方式:

from annoying.decorators import render_to

@render_to('order/item.html')
def item(request, cat_id):
    item_list = get_object_or_404(ItemCategory, pk=cat_id)
    return {'item_list':item_list}
相关问题