for loop iteration in django

戏子无情 提交于 2019-12-12 19:26:43

问题


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))

models:

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

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

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..


回答1:


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.

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

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




回答2:


Django's for tag doesn't provide you with any means to break out of the loop. You'll simply have to filter the collection in your own view and slice it after the point your condition fails and supply that to your template.




回答3:


you could probably use ifchanged tag:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#ifchanged

However, you probably should consider moving this logic to view.




回答4:


If you can structure your if statement to detect when you want to output nothing, you can simply put nothing inside your else clause:

{% 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 %}
         {% if forloop.first %}
             {{post}}
         {%else%}{%endif%}
   {% endif %}      
{% endfor %} 

The above might not do quite what you want - you will have to tweak it yourself. The only thing you can't do is set a flag that this is the first entry into the else clause.



来源:https://stackoverflow.com/questions/10397470/for-loop-iteration-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!