在django中循环迭代 [英] for loop iteration in django

查看:381
本文介绍了在django中循环迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的编码是:
视图

My coding is: views

def showThread(request, thread_id)
    post_list     = Post.objects.filter(id = thread_id)
    post_likes    = PostLikes.objects.all()
    return render_to_response('show.html',locals(),context_instance=RequestContext(request))

型号:

class Post(models.Model):
        subject = models.CharField(max_length = 250)
        body = models.TextField()
        thread = models.ForeignKey('self', null = True, editable = False )

Show.html:

Show.html:

{% for post in post_list %}
   {{post.id}}{{post.subject}}
{% endfor %}
{% for post_like in post_likes %}
   {% if post_like.post_id == post.id and post_like.user_id == user.id %} 
         U like this post{{post}}
   {% else %}
         {{post}}
   {% endif %}      
{% endfor %} 

在show.html,else部分,它会一次又一次显示值。但是我只需要一次。当我进入其他条件时,如何打破for循环。请帮助我..

In the show.html, else part, it displays the values again and again. But i need only one time.How can i break the for loop when i enter into else condition.Please help me..

推荐答案

您可以使用此 django片段页中找到的django自定义模板标签。如果您对使用它有疑问,请转到此页面了解自定义模板标签。

You can use the django custom template tag found in this django snippets page. If you have doubts on using it, go to this page to learn about custom template tags.

然后使用 {%load loop_break%} 在模板中加载模板标签。那么你可以打破for循环,如下所示:

Then load the template tag in your template using {% load loop_break %}. Then you can break the for loop as given below:

{% for post_like in post_likes %}
    {% if post_like.post_id == post.id and post_like.user_id == user.id %} 
        U like this post{{post}}
    {% else %}
        {{post}}
        {{ forloop|break }}
    {% endif %}
{% endfor %}

这里,当进入 else 部分时,for循环将中断。

Here the for loop will break when it enters the else part.

这篇关于在django中循环迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆