像Django Ajax中的Button

时间:2017-10-20 11:41:20

标签: ajax django python-2.7

我的喜欢按钮工作正常,没有ajax页面重新加载,但是通过实现ajax完成时遇到问题。类似和不同的是在后端发生(就像在ajax Post请求中在数据库中创建和删除一样),但类似的计数,例如,不像按钮在ajax post请求的响应中不会改变,直到页面被重新加载。需要帮助

这里是帖子模型和类似的模型,用于发布图像并喜欢在models.py

class PostModel(models.Model):
 user = models.ForeignKey(UserModel)
 image = models.FileField(upload_to='user_images')
 image_url = models.CharField(max_length=255)
 caption = models.CharField(max_length=240)
 created_on = models.DateTimeField(auto_now_add=True)
 updated_on = models.DateTimeField(auto_now=True)
 has_liked = False

 @property
 def like_count(self):
 return len(LikeModel.objects.filter(post=self))

 class LikeModel(models.Model):
  user = models.ForeignKey(UserModel)
  post = models.ForeignKey(PostModel)
  created_on = models.DateTimeField(auto_now_add=True)
  updated_on = models.DateTimeField(auto_now=True)

在urls.py中喜欢的网址

    url(r'^like/', like_view),

views.py

 def like_view(request):
    user = check_validation(request)
    if user and request.method == 'POST':
       form = LikeForm(request.POST)
       if form.is_valid():
           #post_id = form.cleaned_data.get('post').id
           post_id=request.POST['post']

           existing_like = LikeModel.objects.filter(post_id=post_id, user=user).first()

           if not existing_like:
                LikeModel.objects.create(post_id=post_id, user=user)
           else:
                existing_like.delete()

        return redirect('/feed/')

    else:
        return redirect('/login/')

template.html

    {% for post in posts %}
    <form id="like_form">
      {% csrf_token %}
      <input type="hidden" name="post" id="post_id"value="{{ post.id }}">
      {% if post.has_liked %}
      <button class="btn btn-link unlike"type="submit"><i class="fa fa-heart" aria-hidden="true"style="color:#ed4956;"></i></button>
      {% else %}
      <button class="btn btn-link like"type="submit"><i class="fa fa-heart-o" aria-hidden="true"style=color:#333333;"></i></button>
      {% endif %}

     </form>
    {% endfor %}

Javascript代码

      <script>

      $(document).on('submit','#like_form',function (e) {
      e.preventDefault();
      $.ajax({
      type:'POST',
      url:'/like/',
      data:{
      post:$('#post_id').val(),
      csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()

      },
      success:function (response) {
        console.log("liked");
    }

    });

    });
  </script>

0 个答案:

没有答案