2015-04-30 92 views
0

我創建了一個類似按鈕,當用戶喜歡照片時將用戶添加到查詢中,並在與照片不同時將其刪除。像匹配查詢不存在 - Django

後端工程太棒了!前端,不是那麼多。

我收到以下錯誤,當我嘗試加載頁面:Like matching query does not exist.

的問題是在這行代碼:like = Like.objects.get(pk=obj.id)

可能有人請幫助我正確的代碼顯示{% if request.user.username in like.get_likers %}{{ like.likers.count }}在我的HTML文件?

非常感謝!

HTML:

{% if request.user.username in like.get_likers %} 
    <input id="like_btn" name="{{ obj.slug }}" value="Liked" type="button" /> 
{% else %} 
    <input id="like_btn" name="{{ obj.slug }}" value="Like" type="button" /> 
{% endif %} 
<h3> 
    <a href="{% url 'like_thread' %}"><strong id="like_count">{{ like.likers.count }}</strong></a> 
</h3> 

VIEWS.PY:

def photo_detail(request, photo_slug, username): 
    u = MyUser.objects.get(username=username) 
    obj = get_object_or_404(Photo, slug=photo_slug) 
    like = Like.objects.get(pk=obj.id) 

    context = { 
     "like": like, 
     "obj": obj 
    } 
    return render(request, "photos/photo_detail.html", context) 

MODELS.PY:

class Photo(models.Model): 
    creator = models.ForeignKey(MyUser, null=False) 
    image = models.ImageField(upload_to='user/photos/', null=True, blank=True) 
    slug = models.SlugField(null=False, blank=False) 
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) 

class Like(models.Model): 
    image = models.ForeignKey(Photo) 
    likers = models.ManyToManyField(MyUser, related_name='Likers', null=True, blank=True) 
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) 

    def __unicode__(self): 
     return "CREATOR: %s | SLUG: %s" %(self.image.creator, self.image.slug) 

    def get_likers(self): 
     return ", ".join([a.username for a in self.likers.all()]) 
+0

這幾乎是它所說的,沒有任何對象與Like查詢匹配。這張特別的照片有沒有喜歡? – onyeka

+0

@onyeka不,它不。這是我最大的問題。如果它有以前的喜歡,我可以得到的數據沒有問題。這是我最初遇到的麻煩。 – jape

回答

0

您需要檢查是否有喜歡的。無論是在視圖中還是在模板中。由於類似的變量可能有內容或沒有,你可以先檢查視圖。如果存在,請將其添加到字典中。

def photo_detail(request, photo_slug, username): 
    u = MyUser.objects.get(username=username) 
    obj = get_object_or_404(Photo, slug=photo_slug) 

    context = { 
     "obj": obj 
    } 
    # find out if there are any likes, if there are, add 
    # to the context dictionary 
    try: 
     like = Like.objects.get(pk=obj.id) 
     context['like'] = like 
    except Like.DoesNotExist: 
     pass 

    return render(request, "photos/photo_detail.html", context) 

然後在你的模板,你也需要做一個如果:

{% if like %} 
     <input id="like_btn" name="{{ obj.slug }}" value="{% if request.user.username in like.get_likers %}Liked{% else %}Like{% endif %}" type="button" />} 
{% endif %} 

但實際上,你可以很容易地檢查,如果用戶喜歡從視圖中的照片。

+0

非常感謝! – jape