Я пытаюсь настроить функциональность «нравится / не нравится», чтобы, если пользователь просматривает видео (например), страница не обновляет sh и не теряет прогресс в видео. Я понимаю, как изменить содержимое тега <div>
, но понятия не имею, как обращаться с логи c, которые мне нужно будет использовать для изменения текста / URL-адреса кнопки (пример: если они нажимают «нравится», то «лайк» должен стать «непохожим», а URL-адрес, связанный с «лайком», должен быть изменен) Логи c в шаблон замены и удалил то, что у меня было раньше, так что прости меня за то, что я не выставил HTML.
handle_likes. js
(...)
// Handle button clicks
$(".like-btn").on('click', function(){
console.log("Like button was clicked!"); // sanity check
// Get the value of the original button
if ($(".like-btn").val() == "not-liked") {
like_post();
// I figured I could change the value to change the linked url
}
if ($(".like-btn").val() == "is-liked") {
unlike_post();
}
});
// Functions to handle likes/dislikes
function like_post(){
console.log("Like post called...") // sanity check
$.ajax({
url: "posting/liking_post/",
data: {
post_id : $("#post_id").val(), // Need this to get the post
post_type : $("#post_type").val() // This too
},
success: function(data) {
$('.like-count').html(data); //Try to update the count of the likes on post
$('.like-btn').html(data); // Try to change the like button
},
// Show error | display in console
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Please contact an admin; We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
};
(...)
views.py
@login_required
def like_post(request):
"""
Checks if user already liked a post, if not then it will make a like object and assign it to the user and post
"""
print(request.is_ajax())
if request.is_ajax():
post_type = request.GET.get('post_type')
post_id = request.GET.get('post_id')
if post_type and post_id:
post = toolz.get_post(int(post_id), post_type)
else:
raise Exception("Post info not passed") # If like button clicked twice, no info is passed
try:
likes = list(Like.objects.filter(object_id=post_id))
if len(likes) > 0:
print("\n\n", likes, "\n\n") # debug
users = list()
for i in likes:
users.append(i.user)
if request.user in users:
print("User has liked this post")
return HttpResponse("Trying to like post twice...is a no no") # just a debug for myself
else:
like = Like(
user=request.user,
content_object=post
)
like.save()
toolz.get_post(post_id, post_type, editing=True).update(like_count=F('like_count') + 1)
like_count = post.like_count
print("DEBUG 456 in like_post; user like list:", likes)
user_liked = True
return render(None, 'like_count.html' ,{'like_count': like_count, 'user_liked': user_liked})
except Exception as e:
print("\nSilent Exception; Error:", e)
else:
raise Exception("Request is not AJAX")