Raji
Raji

Reputation: 571

for loop iteration in 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))

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

Upvotes: 2

Views: 3940

Answers (4)

arulmr
arulmr

Reputation: 8836

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.

Upvotes: 2

Marcin
Marcin

Reputation: 49826

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.

Upvotes: 1

frnhr
frnhr

Reputation: 12903

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.

Upvotes: 1

Filip Dupanović
Filip Dupanović

Reputation: 33660

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.

Upvotes: 5

Related Questions