小编joh*_*ohn的帖子

循环Django模板中的对象列表

似乎无法看到我在哪里出错了.原谅我,因为我是新手.我试图在模型中显示10个最新的对象.

这是我用来将所有这些对象放在列表中的循环:

 # put the top 10 newest Recipe objects in a list   
    entries_list = []
    all_recipes = Recipes.objects.annotate(Count('id'))
    newest_recipe_index = len(all_recipes)
    index = 0
    while index < 10:
        try:
            x = Recipes.objects.get(id=newest_recipe_index)
            entries_list.append(x)
            newest_recipe_index = newest_recipe_index - 1
            index = index + 1
        except:
            index = index + 1
            pass
Run Code Online (Sandbox Code Playgroud)

然后我将其渲染到页面,如下所示:

 c = RequestContext(request, {'form' : form, 'entries_list' : entries_list})
    return render_to_response("main.html", c)
Run Code Online (Sandbox Code Playgroud)

这是我的HTML:

{% for entries in entries_list %}
        <i><b>Name:</i></b> {{ entries_list.name }}<br>
        <img src="/images{{ entries_list.picture }}" height="300" …
Run Code Online (Sandbox Code Playgroud)

python django templates models

8
推荐指数
1
解决办法
1万
查看次数

标签 统计

django ×1

models ×1

python ×1

templates ×1