2014-06-12 74 views
0

我正在嘗試爲我的網絡應用實現Like功能。下面是代碼:Django中的功能特徵

型號:

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

查看:

def like(request): 
    vars = {} 
    if request.method == 'POST': 
     user = request.user 
     slug = request.POST.get('slug', None) 
     doctor = get_object_or_404(Doctor, slug=slug) 

     liked, created = Like.objects.create(Doctor=doctor) 

     try: 
      user_liked = Like.objects.get(Doctor=doctor, user=user) 
     except: 
      user_liked = None 

     if user_liked: 
      user_liked.total_likes -= 1 
      liked.user.remove(request.user) 
      user_liked.save() 
     else: 
      liked.user.add(request.user) 
      liked.total_likes += 1 
      liked.save() 


    return HttpResponse(simplejson.dumps(vars), 
       mimetype='application/javascript') 

網址:

url(r'^like/(?P<id>\d+)/$', views.like, name='like'), 

模板:

<input type="button" id="like" name="{{doctor_slug}}" value="Like" /> 

<script> 
$('#like').click(function(){ 
     $.ajax({ 
       type: "POST", 
       url: "{% url like %}", 
       data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'}, 
       dataType: "text", 
       success: function(response) { 
         alert('You liked this') 
       }, 
       error: function(rs, e) { 
         alert(rs.responseText); 
       } 
      }); 
    }) 
</script> 

當我打開我的模板頁面時,出現錯誤NoReverseMatch at /docprofile/1/ 'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs.我查看了文檔,但找不到任何可以在此處使用的內容。問題似乎在"url: "{% url like %}","的模板中。這是在Ajax裏面。

+0

您需要告訴django哪個id想要url反向轉換才能正常工作。 – tbrisker

回答

0

如錯誤所述,您應該看到docs。您需要將路徑傳遞給視圖函數或將url的名稱作爲字符串傳遞給url模板標記。

<script> 
$('#like').click(function(){ 
     $.ajax({ 
       type: "POST", 
       url: "{% url 'like' %}", 
       data: {'slug': $(this).attr('name'), 'csrfmiddlewaretoken': '{{csrf_token}}'}, 
       dataType: "text", 
       success: function(response) { 
         alert('You liked this') 
       }, 
       error: function(rs, e) { 
         alert(rs.responseText); 
       } 
      }); 
    }) 
</script> 
+0

謝謝!這解決了問題。 – maahd