Django + AJAX 中的“点赞”按钮

问题描述 投票:0回答:0

我想在我的项目中实现一个点赞按钮。我想在不重新加载页面的情况下做到这一点,所以我搜索并决定使用 JS 的 AJAX,但是有一个问题,我对 Javascript 的知识绝对为零,我不知道这***是如何工作的。

所以,看看我的代码,我希望有人能帮助我
或者我就是一条死胡同
提前致谢:)

这是views.py

def like_place(request, pk):
    print(request.method)
    if request.method == "POST":
        place = Place.objects.get(id=pk)
        user = request.user

        if user in place.place_likes.all():
            place.place_likes.remove(user)
        else:
            place.place_likes.add(user)

        place_likes_count = place.place_likes.count()

        return JsonResponse({'likes_count': place_likes_count})
    else:
        return JsonResponse({'error': 'Invalid request.'}, status=400)

这是我的html页面

 <div class="search-and-filters">
    <form action="" method="GET">
      <input type="text" name="search_query" placeholder="Search by cafe name">
      <select name="country_filter" style="text-align: center;">
        <option value="">Search by country</option>
      </select>
      <select name="city_filter">
        <option value="">Search by city</option>
      </select>
      <button type="submit">Find Place</button>
    </form>
  </div>

  <div class="feed-container">
    <div class="comments-section">
        <div class="comment">
          <div class="comment-nickname">Никнейм</div>
          <div class="comment-details">commented at (название заведения)</div>
          <div class="comment-text">Комментарий</div>
          <div class="comment-date">3 дня назад</div>
        </div>
      </div>

    <div class="posts-section">
      <div class="post">
      {% for place in places %}
      <div class="post-title"><a href="{% url 'place_page' place.id %}" style="color: black;">{{ place.place_name }}</a></div>
      <form method="post">
        {% csrf_token %}
        <button class="button button-like like-button" data-place-id="{{ place.id }}" style="border: none; background-color: transparent" name="like-button">
          <i class="{% if user in place.place_likes.all %}fas{% else %}far{% endif %} fa-heart like-icon"></i>
          <span id="like-count-{{ place.id }}">{{ place.number_of_likes }}</span>
        </button>
      </form>
      <div class="post-details">
        <div class="post-info">
          <div class="user-info">
            <span class="posted-by">Posted by <a href="{% url 'profile_page' place.created_by.id %}" style="color: black;"><b>{{ place.created_by.username }}</b></a></span>
            <span class="date">at {{ place.created }}</span>
          </div>
          <div class="cafe-info">
            <div>{{ place.place_country }}, {{ place.place_city }}</div>
            <div>{{ place.place_street }}</div>
            <div> Place Rating : {{ place.place_rating }}/10</div>
            <div> Coffee Rating : {{ place.coffee_rating }}/10</div>
          </div>
        </div>
        <div class="post-image">
          <a href="{% url 'place_page' place.id %}">
          <img src="{{ place.place_photo.url }}" alt="Cafe Photo"  style="width: 100%; height: 100%; object-fit: cover; border-radius: 5px; margin-bottom: 20px;">
          </a>
        </div>
      </div>
      {% endfor %}
      </div>
    </div>

    <div class="friends-section">
      <ul class="friend-list">
        <li class="friend-item"></li>
        <li class="friend-item"></li>
      </ul>
    </div>
  </div>
{% endblock %}


{% block javascript %}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
        $(input[name="like-button"]).bind('click', function() {
            console.log('hello111')
            print('hello')
            event.preventDefault();
            const placeId = $(this).data("place-id");
            const url = `{% url 'like_place' 0 %}`.replace('0', placeId);

            $.post(url, function(data) {
                if ('likes_count' in data) {
                    const placeLikesCount = data.likes_count;
                    $(`#like-count-${placeId}`).text(placeLikesCount);
                } else {
                    console.error('Ошибка в ответе AJAX:', data);
                }
            });
        });
    });
</script>
{% endblock %}

所以,如果您需要,这是我的数据库模型

class Place(models.Model):     
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    place_name = models.CharField(max_length=200)
    place_country = models.ForeignKey('cities_light.Country', on_delete=models.SET_NULL, null=True, blank=True) 
    place_city = models.ForeignKey('cities_light.City', on_delete=models.SET_NULL, null=True, blank=True) #### LINK CITY TO THE COUNTRY RELS
    place_street = models.CharField(max_length=200)
    place_photo = models.ImageField(null=False)
    place_likes = models.ManyToManyField(User, related_name='place_like')
    description = models.TextField(null=False)
    place_rating = models.FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(10.0)])
    coffee_rating = models.FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(10.0)])
    wifi_good = models.BooleanField(default=False)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)
javascript python django ajax web
© www.soinside.com 2019 - 2024. All rights reserved.