Уникальная кнопка отправки для каждого пользователя - django
У меня есть кнопка Like для моих постов, которые могут нравиться пользователям или нет, что означает, что если пользователь нажал на кнопку в первый раз, то пост ему понравится, а во второй раз - не понравится.
Как в Facebook, twitter и т.д. Я много раз пытался сделать это, но проблема в том, что "когда пользователь нажимает на кнопку, она добавляет один лайк в счетчик и если пользователь ставит лайк снова, то считается 2 лайка за пост пользователя!
".
Как сделать так, чтобы лайки были уникальными? Каждый пользователь должен иметь возможность поставить лайк только один раз, и если он нажал на кнопку еще раз, это означает, что ему не понравился пост.
if request.POST.get("single_tweet_like_submit_btn"):
try:
# Debug: Check the request and user
print(f"Request by user: {current_basic_user_profile.user.username} for tweet ID: {current_tweet.id}")
# Check if the user has already liked the tweet
tweet_like = TweetLike.objects.filter(tweet=current_tweet, liker=current_basic_user_profile)
if tweet_like:
# Debug: User has already liked the tweet, so we'll unlike it
print(f"User {current_basic_user_profile.user.username} has already liked tweet {current_tweet.id}, unliking it.")
# If the user has already liked the tweet, unlike it
tweet_like.delete()
# Decrement the like count
current_tweet.tweet_like_amount = max(0, current_tweet.tweet_like_amount - 1)
else:
# Debug: User has not liked the tweet yet, so we'll like it
print(f"User {current_basic_user_profile.user.username} has not liked tweet {current_tweet.id}, liking it.")
# If the user hasn't liked the tweet, like it
new_like = TweetLike(tweet=current_tweet, liker=current_basic_user_profile)
new_like.save()
# Increment the like count
current_tweet.tweet_like_amount += 1
# Create a notification for the like
new_notification = NotificationLike(
notified=current_tweet.user,
notifier=current_basic_user_profile,
tweet=current_tweet,
)
new_notification.save()
# Save the current tweet's state
current_tweet.save()
# Debug: Output the new like count
print(f"Tweet {current_tweet.id} now has {current_tweet.tweet_like_amount} likes.")
except Exception as e:
# Handle exceptions appropriately
print(f"An error occurred: {e}") # For debugging purposes
return HttpResponseRedirect(f"/tweet/{current_tweet.id}/")
Я перепробовал множество способов решения проблемы, но безуспешно :)
Ваш подход почти корректен, убедитесь, что пользователю может понравиться или не понравиться сообщение только один раз, вам нужно проверить, существует ли уже лайк, а затем либо удалить его, либо добавить, соответственно корректируя количество лайков.
if request.POST.get("single_tweet_like_submit_btn"):
try:
print(f"Request by user: {current_basic_user_profile.user.username} for tweet ID: {current_tweet.id}")
# Toggle like status
tweet_like, created = TweetLike.objects.get_or_create(tweet=current_tweet, liker=current_basic_user_profile)
if created:
print(f"User {current_basic_user_profile.user.username} liked tweet {current_tweet.id}.")
current_tweet.tweet_like_amount += 1
NotificationLike.objects.create(
notified=current_tweet.user,
notifier=current_basic_user_profile,
tweet=current_tweet,
)
else:
print(f"User {current_basic_user_profile.user.username} unliked tweet {current_tweet.id}.")
tweet_like.delete()
current_tweet.tweet_like_amount = max(0, current_tweet.tweet_like_amount - 1)
current_tweet.save()
print(f"Tweet {current_tweet.id} now has {current_tweet.tweet_like_amount} likes.")
except Exception as e:
print(f"An error occurred: {e}")
return HttpResponseRedirect(f"/tweet/{current_tweet.id}/")
Мой код использует get_or_create, чтобы упростить процесс проверки того, существует ли уже объект like, и соответствующим образом изменяет статус like.