2014-03-04 81 views
0

model.pyDjango的:在查詢列表當前登錄用戶

class Question(models.Model): 
    user = models.ForeignKey(User) 
    title = models.CharField(max_length= 200) 
    description = models.TextField() 
    location = models.CharField(max_length=150) 
    tags = TaggableManager() 
    time = models.DateTimeField(auto_now_add=True) 

    def __unicode__(self): 
     return self.title 


class Like(models.Model): 
    user = models.ManyToManyField(User, related_name='likes') 
    question = models.ForeignKey(Question) 
    date = models.DateTimeField(auto_now_add=True) 
    likecount = models.IntegerField(default=0) 

urls.py

url(r'^$', ListView.as_view(queryset= Question.objects.all(), 
       template_name="index.html")), 

的index.html

{%for question in object_list %} 
    {%for user_liked in question.like_set.all%} 
     {% if user.username in user_liked.user.all%} `<!--if current logged in user in Like model user m2m field-->` 
     <button type="button" class="btn btn-disable" name= {{question.id}}"id="request">Liked </button> <!--disable like button--> 
    {%else%} 
     <button type="button" class="btn btn-enable" name= {{question.id}}"id="request">Like </button> <!--enable like button--> 
    {%endif%} 
    {%endfor%} 
{%endfor%} 

問題是if template tag塊不起作用。

回答

1

它可以工作,但是like_set.all不是用戶名列表,而是用戶列表。因此檢查user.username是否在用戶列表中失敗。檢查用戶是否在like_set.all中。

+0

謝謝,明白了:) – MysticCodes

+0

不客氣。 –

相關問題