题目
Django如何简单实现点赞功能
步骤
1.前期准备
用户models.py
class User(models.Model):
username = models.CharField("用户名",max_length=10)
点赞models.py LikeNum的作用在于当有人点赞时可以把它记录下来,包括点赞者和点赞的内容
class LikeNum(models.Model):
user = models.ForeignKey(UserInfos,null=True,on_delete=models.SET_NULL)
discussion = models.ForeignKey(Discussion,null=True,on_delete=models.SET_NULL)
class Meta:
verbose_name_plural = 'user'
发布models.py Discusssion的作用在于渲染前端页面,里边包括动态发布人和被点赞数量
class Discussion(models.Model):
user = models.ForeignKey(UserInfos,null=True,on_delete=models.SET_NULL)
likes = models.PositiveIntegerField("喜欢",default=0,editable=False)
class Meta:
verbose_name_plural = 'Discussion'
views.py
def addLikes(request,id):
if request.session.get('username') and request.session.get('uid'):
username = request.session.get('username')
user = UserInfos.objects.get(username=username)
else:
return HttpResponseRedirect('/error')
try:
if Discussion.objects.get(id=id):
d = Discussion.objects.get(id=id)
if user:
record,flag = LikeNum.objects.get_or_create(user=user,discussion=d)
if flag:
d.likes+=1
d.save()
else:
d.likes -= 1
d.save()
LikeNum.objects.get(user=user,discussion=d).delete()
return render(request,'page.html',{'page':Discusssion.objects.all(),'ln':LikeNum.objects.fitter(user=user)})
else:
return redirect('/login')
except Exception as e:
return HttpResponseRedirect('/error')
2.html实现
{% for item in page %}
<div>
用户名:{{item.user.username}}
<a id="id{{item.id}}">
<svg class="icon" aria-hidden="true">
<use xlink:href="#icon-like-fill"></use>
</svg>
<span id="nlikes">{{item.likes}}</span>
</a>
</div>
<!-- 请把我写在这里 3.js实现 --!>
{% endfor %}
3.js实现【!!!注意这段代码写在for循环之内】
{% if ln %}
{% for l in ln %}
{% if l.discussion == item %}
<script>
obj = document.getElementById('id{{item.id}}');
obj.className = 'success';
</script>
{% endif %}
{%endfor%}
{%endif%}
4.css实现
.success {
color: #fc5531;
text-decoration: none;
}
a {
text-decoration: none;
color: #848B96;
}
a:hover {
color: #fc5531;
}
这只是一个大概流程,具体的美化还需要自己实现,不懂得话可以留言来交流!
示意图【我自己做出来的效果】
|