我在我的一个页面的上下文中有一个名为 comments 的列表,当我迭代它时,我想知道item的索引;我想知道这个for循环中 comment 的索引:
<!-- comment list section -->
<div class="card shadow my-3 p-5">
<h3>Comments:</h3>
<!-- checking if any comment exist on this post -->
{% if comments.count < 1 %}
No comments. write the first one!
{% else %}
<!-- iterating on comments and showing them -->
{% for comment in comments %}
<div id="comment-div">
<span id="Comment-name">by: {{ comment.name }}</span>
<span id="Comment-date">{{ comment.datetime_created|date:'M d Y' }}</span>
<p id="Comment-body">{{ comment.body }}</p>
</div>
{% endfor %}
{% endif %}
</div>
浏览次数:
class PostDetailView(FormMixin, generic.DetailView):
model = Post
template_name = 'blog/post_detail.html'
context_object_name = 'post'
form_class = CreateComment
def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs) # get the default context data
context['comments'] = Comment.objects.filter(accepted=True) # add extra field to the context
return context
型号:
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
email = models.EmailField(max_length=35)
name = models.CharField(max_length=50)
body = models.TextField()
datetime_created = models.DateTimeField(auto_now_add=True)
accepted = models.BooleanField(default=False)
1条答案
按热度按时间esbemjvw1#
您可以使用foorloop.counter或forloop.counter0
还有一些其他方便的工具。查看'for'内置的文档