访问django模板中的列表项

Accessing list item in django template

我有一个列表,rate_text ['', 'Disappointed', 'Not Promissing', 'OK', 'Good', 'Awesome'] 在从视图呈现的模板中。我可以使用 {{rate_text.index}} 访问其中的任何项目,如下所示:

{% for review in reviews %}
<div class="panel panel-info" style='border-color:#ffffff;'>
    <div class="panel-heading" >
        <h3 class="panel-title lead">{{review.title}}</h3>
    </div>
    <div class="panel-body">
       <p class='text-center'>{{review.review}}</p>
       <h5 class='text-right'>-{{review.username}} ( {{review.email}} ) </h5>
       <h5 class='text-right'>Rating : {{rate_text.4}}</h5>
    </div>
</div>
<hr>
{% endfor %}

但是,我不想在 {{rate_text.index}} 中使用索引,而是想使用 {{review.rating}} 作为索引。有什么办法可以做到这一点?? 提前致谢。

最佳选择是对 rating 字段使用 choices 属性:

RATING_CHOICES = list(enumerate(['', 'Disappointed', 'Not Promissing',
                                 'OK', 'Good', 'Awesome']))

class Review(models.Model):
    ...
    rating = models.IntegerField(..., choices=RATING_CHOICES)

然后在模板中使用:

{{ review.get_index_display }}

另一种选择是使用 custom template filter:

@register.filter
def get_by_index(lst, idx):
    return lst[idx]

模板将如下所示:

{{ rate_text|get_by_index:review.rating }}