Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 604
Raji Avatar asked Jun 03 '26 01:06

Raji


1 Answers

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.

like image 110
Filip Dupanović Avatar answered Jun 05 '26 18:06

Filip Dupanović



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!