喜欢Django的功能

时间:2014-06-12 21:14:50

标签: python ajax django url django-templates

我正在尝试为我的网络应用实施类似功能。这是代码:

型号:

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:

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中。

1 个答案:

答案 0 :(得分: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>