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里面的。
1 个回答
0
根据错误提示,你应该查看一下文档。你需要把视图函数的路径或者网址的名字以字符串的形式传递给网址模板标签。
<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>