django ajax 点赞按钮 css 类
django ajax like button with css classes
你好,我有一个 post 模型,它有一个 like(m2m) 和 user(forgeinkey) 模型字段,我正在尝试检查 request.user 是否喜欢 post 和如果他们有,我应该向他们显示一个红色的心形按钮,否则应该显示一个蓝色的心形按钮,现在因为有多个 post 和喜欢,我循环遍历每个喜欢的对象以检查 request.user 是否有喜欢与否。不幸的是,出于某种原因,我无法实现良好的逻辑,而且我看到每个用户都有类似的按钮。一些帮助将不胜感激。
这是我的模型:
class post(models.Model):
user = models.ForeignKey(User,default='' , related_name='has_liked', on_delete=models.CASCADE)
caption = models.CharField(max_length=100)
image = models.FileField(upload_to='images/', null=True, blank=True)
video = models.FileField(upload_to='videos/', null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
like = models.ManyToManyField(User, null=True, blank=True, default='')
观点:
@login_required
def usersfeed(request):
users = User.objects.all()
posts = post.objects.filter(Q(user__in=request.user.profile.friend.all()) | Q(user=request.user)).order_by('-created')
comments = Comment.objects.all()
status_form = StatusForm(request.POST)
friend_requests = FriendRequest.objects.filter(to_user=request.user)
friends = request.user.profile.friend.all()
for i in posts:
likes = i.like.all()
print(likes)
for like in likes:
if like.username == request.user.username:
if request.user:
Hasliked = True
print('liked')
else:
Hasnotliked = True
print('not liked')
context = {
'Post':posts,
'User':users,
'form':PostForm(),
'Profile':profile,
'Form':CommentForm(),
'Comment':comments,
'Status':status_form,
'fr':friend_requests,
'friend':friends,
'Hasliked':Hasliked,
'Hasnotliked':Hasnotliked,
}
return render(request, 'social_media/feed.html', context=context)
ajax 点赞计数器的视图:
@login_required
def like_post(request):
Post = get_object_or_404(post, id=request.GET.get('post_id'))
cssClass = 'colorRed'
if Post.like.filter(id=request.user.id).exists():
Post.like.remove(request.user)
else:
Post.like.add(request.user)
count = Post.like.count()
users = Post.like.all()
user = []
for i in users:
user.append((i.username))
response = {
'count':count,
'users':user,
'cssClass':cssClass,
}
return JsonResponse(response)
Html代码:
{% for i in Post %}
<form action="{% url 'like_post' %}" class='like-submit' data-catid="{{ i.id }}" method="GET">
<div class="like">
{% if Hasliked == True %}
<button id="likeBtn{{ i.id }}" class="likeClassBtn colorRed">
<i class="fas fa-heart"></i>
</button>
{% endif %}
{% if Hasnotliked == True %}
<button id="likeBtn{{ i.id }}" class="likeClassBtn">
<i class="fas fa-heart"></i>
</button>
{% endif %}
<div class="show_likes">
<span id="likes_count{{ i.id }}">{{ i.total_likes }}</span>
<div class="username_liked">
<div id="user-likes{{ i.id }}" class="user-likes">
{% for p in i.like.all %}
{{ p.username }}
{% endfor %}
</div>
</div>
</div>
</div>
</form>
{% endfor %}
<script>
$(document).ready(function () {
$(".like-submit").submit(function (event) {
event.preventDefault()
const url = $(this).attr('action');
const catid = $(this).attr("data-catid");
$.ajax({
type: "GET",
url: url,
data: {
post_id: catid,
},
success: function (data) {
$('#likes_count' + catid).html(data.count)
if ($('#user-likes' + catid).html()){
$('#user-likes' + catid).html(data.users + ' ')
$('#likeBtn' + catid).toggleClass(data.cssClass)
}
}
});
});
});
</script>
您需要将 hasLiked/hasNotLiked 存储在该用户的 post 记录中。上面的代码暗示所有 post 都被喜欢或不喜欢。您还需要重新考虑加载上下文的方式——当前代码效率极低。我建议用 id 数组替换 Hasliked 和 Hasnotliked 上下文条目,其中每个条目将包含当前用户 liked/disliked 的 post 的 ID。然后在模板中检查:
{% if i.id in Hasliked %}
<button id="likeBtn{{ i.id }}" class="likeClassBtn colorRed">
<i class="fas fa-heart"></i>
</button>
{% endif %}
{% if i.id in Hasnotliked %}
<button id="likeBtn{{ i.id }}" class="likeClassBtn">
<i class="fas fa-heart"></i>
</button>
{% endif %}
可以使用您当前的设置加载喜欢和不喜欢的内容:
friends = request.user.profile.friend.all()
for i in posts:
likes = i.like.all()
print(likes)
for like in likes:
if like.username == request.user.username:
if request.user:
Hasliked.append(i.id)
print('liked')
else:
Hasnotliked.append(i.id)
print('not liked')
这样效率极低,最好的办法是直接查询数据库,直接返回ids:
l_likedPosts = PostActions.objects.filter(user_id=l_currUser,
喜欢=真)
.values_list('post_id',平=真)
喜欢 = 列表(l_likedPosts)
上面的代码假定您有一个 table PostActions,它至少包含 user_id、post_id 和 liked/disliked 状态。这通常是 manytomany 字段在幕后为您所做的,但是在更复杂的数据模型中使用它需要太多的自由。
你好,我有一个 post 模型,它有一个 like(m2m) 和 user(forgeinkey) 模型字段,我正在尝试检查 request.user 是否喜欢 post 和如果他们有,我应该向他们显示一个红色的心形按钮,否则应该显示一个蓝色的心形按钮,现在因为有多个 post 和喜欢,我循环遍历每个喜欢的对象以检查 request.user 是否有喜欢与否。不幸的是,出于某种原因,我无法实现良好的逻辑,而且我看到每个用户都有类似的按钮。一些帮助将不胜感激。
这是我的模型:
class post(models.Model):
user = models.ForeignKey(User,default='' , related_name='has_liked', on_delete=models.CASCADE)
caption = models.CharField(max_length=100)
image = models.FileField(upload_to='images/', null=True, blank=True)
video = models.FileField(upload_to='videos/', null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
like = models.ManyToManyField(User, null=True, blank=True, default='')
观点:
@login_required
def usersfeed(request):
users = User.objects.all()
posts = post.objects.filter(Q(user__in=request.user.profile.friend.all()) | Q(user=request.user)).order_by('-created')
comments = Comment.objects.all()
status_form = StatusForm(request.POST)
friend_requests = FriendRequest.objects.filter(to_user=request.user)
friends = request.user.profile.friend.all()
for i in posts:
likes = i.like.all()
print(likes)
for like in likes:
if like.username == request.user.username:
if request.user:
Hasliked = True
print('liked')
else:
Hasnotliked = True
print('not liked')
context = {
'Post':posts,
'User':users,
'form':PostForm(),
'Profile':profile,
'Form':CommentForm(),
'Comment':comments,
'Status':status_form,
'fr':friend_requests,
'friend':friends,
'Hasliked':Hasliked,
'Hasnotliked':Hasnotliked,
}
return render(request, 'social_media/feed.html', context=context)
ajax 点赞计数器的视图:
@login_required
def like_post(request):
Post = get_object_or_404(post, id=request.GET.get('post_id'))
cssClass = 'colorRed'
if Post.like.filter(id=request.user.id).exists():
Post.like.remove(request.user)
else:
Post.like.add(request.user)
count = Post.like.count()
users = Post.like.all()
user = []
for i in users:
user.append((i.username))
response = {
'count':count,
'users':user,
'cssClass':cssClass,
}
return JsonResponse(response)
Html代码:
{% for i in Post %}
<form action="{% url 'like_post' %}" class='like-submit' data-catid="{{ i.id }}" method="GET">
<div class="like">
{% if Hasliked == True %}
<button id="likeBtn{{ i.id }}" class="likeClassBtn colorRed">
<i class="fas fa-heart"></i>
</button>
{% endif %}
{% if Hasnotliked == True %}
<button id="likeBtn{{ i.id }}" class="likeClassBtn">
<i class="fas fa-heart"></i>
</button>
{% endif %}
<div class="show_likes">
<span id="likes_count{{ i.id }}">{{ i.total_likes }}</span>
<div class="username_liked">
<div id="user-likes{{ i.id }}" class="user-likes">
{% for p in i.like.all %}
{{ p.username }}
{% endfor %}
</div>
</div>
</div>
</div>
</form>
{% endfor %}
<script>
$(document).ready(function () {
$(".like-submit").submit(function (event) {
event.preventDefault()
const url = $(this).attr('action');
const catid = $(this).attr("data-catid");
$.ajax({
type: "GET",
url: url,
data: {
post_id: catid,
},
success: function (data) {
$('#likes_count' + catid).html(data.count)
if ($('#user-likes' + catid).html()){
$('#user-likes' + catid).html(data.users + ' ')
$('#likeBtn' + catid).toggleClass(data.cssClass)
}
}
});
});
});
</script>
您需要将 hasLiked/hasNotLiked 存储在该用户的 post 记录中。上面的代码暗示所有 post 都被喜欢或不喜欢。您还需要重新考虑加载上下文的方式——当前代码效率极低。我建议用 id 数组替换 Hasliked 和 Hasnotliked 上下文条目,其中每个条目将包含当前用户 liked/disliked 的 post 的 ID。然后在模板中检查:
{% if i.id in Hasliked %}
<button id="likeBtn{{ i.id }}" class="likeClassBtn colorRed">
<i class="fas fa-heart"></i>
</button>
{% endif %}
{% if i.id in Hasnotliked %}
<button id="likeBtn{{ i.id }}" class="likeClassBtn">
<i class="fas fa-heart"></i>
</button>
{% endif %}
可以使用您当前的设置加载喜欢和不喜欢的内容:
friends = request.user.profile.friend.all()
for i in posts:
likes = i.like.all()
print(likes)
for like in likes:
if like.username == request.user.username:
if request.user:
Hasliked.append(i.id)
print('liked')
else:
Hasnotliked.append(i.id)
print('not liked')
这样效率极低,最好的办法是直接查询数据库,直接返回ids:
l_likedPosts = PostActions.objects.filter(user_id=l_currUser,
喜欢=真)
.values_list('post_id',平=真)
喜欢 = 列表(l_likedPosts)
上面的代码假定您有一个 table PostActions,它至少包含 user_id、post_id 和 liked/disliked 状态。这通常是 manytomany 字段在幕后为您所做的,但是在更复杂的数据模型中使用它需要太多的自由。