我正在尝试使用AJAX在Django中实现一个赞按钮。我的模型是:
class post(models.Model):
Profile=models.ForeignKey(Profile,on_delete=models.CASCADE)
Picture=models.ImageField(upload_to='PostMedia',blank=True,null=True)
DatePosted=models.DateTimeField(default=timezone.now)
Content=models.TextField(blank=True,null=True)
user_like=models.ManyToManyField(User,related_name="likes",blank=True)
def __str__(self):
return self.Profile.user.username
@property
def totallikes(self):
return self.user_like.count()
class Meta:
ordering=['-DatePosted']
@property
def like_count(self):
return len(likes.objects.filter(post=self))
我的网址是:-
path('like/',views.like_button,name='like_button'),
我的查看功能是:-
def like_button(request):
if request.method=='POST':
user=request.user
postobject=get_object_or_404(post,pk=id)
if postobject.likes.filter(id=user.id).exists():
postobject.likes.remove(user)
else:
postobject.likes.add(user)
context={'likes_count':postobject.total_likes}
return HttpResponse(json.dumps(context),content_type='application/json')
最终模板是:-
{% for p in result %}
<div class="SpriteContainer">
<input type="button" class="like" name="{{ p.id }}" value="Like">
<p>{{ p.totallikes }}</p>
</div>
{% endfor %}
<script>
$('.like').click(function(){
var pk=$(this).attr('name')
$.ajax({
type:"POST"
url:"{% url 'like_button' %}"
data:{'pk':pk,'csrfmiddlewaretoken':'{{ csrf_token }}'}
dataType:"json"
success:function(response){
alert('Company likes count is now'+response.count_likes);
}
error:function(rs,e){
alert('Something went wrong')
}
});
})