joh*_*ohn 8 python django templates models
似乎无法看到我在哪里出错了.原谅我,因为我是新手.我试图在模型中显示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" width="300"></img><br>
<i><b>Ingredients:</i></b> {{ entries_list.ingredients }}<br>
<p><i>{{ entries_list.description }}</i></p>
<i><b>Created by:</i></b> {{ entries_list.user }}<br><br>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
这是models.py:
class Recipes(models.Model):
name = models.CharField(max_length=50)
ingredients = models.CharField(max_length=300)
picture = models.ImageField(upload_to = 'recipes/%Y/%m/%d')
user = models.CharField(max_length=30)
date = models.DateTimeField(auto_now=True)
description = models.TextField()
comments = models.ManyToManyField(Comments)
Run Code Online (Sandbox Code Playgroud)
似乎循环正在运行.那里有正确数量的条目.只是模板标签不起作用.他们只是空白.所以看起来这很好地将对象放在列表中,它只是不会检索我的单个字段.
有几件事.您可以通过这种方法订购查询,然后获取前十个条目.它比你拥有的循环更有效.
您的模板不起作用的原因是您指的是列表而不是单个条目.它应该是:
{% for entry in entries_list %}
<i><b>Name:</i></b> {{ entry.name }}<br>
<img src="/images{{ entry.picture }}" height="300" width="300"></img><br>
<i><b>Ingredients:</i></b> {{ entry.ingredients }}<br>
<p><i>{{ entry.description }}</i></p>
<i><b>Created by:</i></b> {{ entry.user }}<br><br>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
一旦模板工作,请尝试以获取您的entries_list:
entries_list = Recipes.objects.order_by('-id')[0:10]
Run Code Online (Sandbox Code Playgroud)
这是关于排序和切片查询的文档:https: //docs.djangoproject.com/en/dev/topics/db/queries
| 归档时间: |
|
| 查看次数: |
10024 次 |
| 最近记录: |