简体   繁体   中英

Looping over a list of objects within a Django template

Can't seem to see where I am going wrong here. Forgive me because I am new to this. I am trying to display the 10 newest objects within a model.

Here is the loop I used to put all of these objects within a list:

 # 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

I then render this to the page like so:

 c = RequestContext(request, {'form' : form, 'entries_list' : entries_list})
    return render_to_response("main.html", c)

And here is my 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 %}

And here is 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)

It seems that the loop is working. The correct amount of entries are there. It is just that the template tags aren't working. They are just blank. So it seems this is working just fine putting the objects inside the list, it just won't retrieve my individual fields.

A couple of things. There is a method by which you can order your query and just get the first ten entries. It would be more efficient than the loop you have.

The reason your template doesn't work is that you're referring to the list rather than the individual entry. It should be:

{% 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 %}

Once you get your template working, try this to get your entries_list:

entries_list = Recipes.objects.order_by('-id')[0:10]

Here's the docs on sorting and slicing queries: https://docs.djangoproject.com/en/dev/topics/db/queries

So what you did: If you know basic of C language.. Your problem is to print element of array, So you will go like..

array = [1,2,3,4,5,6,7]
int i=0;
for(i=0;i<8;i++) {
       print i;      // print array; is wrong
}

Similarly in the above case you are iterating over entries_list and assigning each element to the variable entries . Now you will play with entries .

{% for entries in entries_list %}
        <i><b>Name:</i></b> {{ entries.name }}<br>
        <img src="/images{{ entries.picture }}" height="300" width="300"></img><br>
        <i><b>Ingredients:</i></b> {{ entries.ingredients }}<br>
        <p><i>{{ entries.description }}</i></p>
{% endfor %}

And ofcourse @CarL has given you a better solution for getting latest 10 recipes in case of your models.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM