0

网址.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'),
)

视图.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})

项目.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 %}



鉴于上述代码,它应该显示:

第一类

- item 1
- item 2

但它只是这样显示:

第一类

它不显示项目

这可能有什么问题?

4

1 回答 1

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]

(题外话)有 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}
于 2012-04-28T07:56:49.797 回答