触发JavaScript actionListener时如何在模型内运行方法?

时间:2019-04-10 22:01:54

标签: javascript python django django-models

我有下一个型号:

class Post(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    title = models.CharField(max_length = 200)
    text = models.TextField()
    created_date = models.DateTimeField(default = timezone.now)
    likes = models.IntegerField(default=0)
    tags = models.CharField(max_length = 50, default = '' )

    def process_likes(self):
        like = self.likes = F('likes')+1
        like.save()

    def split_tags(self):
        return self.tags.split()

    def get_absolute_url(self):
        return reverse('blog:post_list')

    def __str__(self):
        return self.title

我想要做的是单击模板中的图标时,我希望运行process_likes方法,该方法将使likes的值增加1。 我的脚本如下:

<script>
    let corazon = document.querySelector('.icon-heart-empty');
    corazon.addEventListener('click', ()=>{
        corazon.classList.toggle('icon-heart');
    });
</script>

我在这里切换图标的类以显示是否单击或不喜欢,但是如何使用纯JavaScript调用process_like方法?

1 个答案:

答案 0 :(得分:0)

您需要使用AJAX调用向服务器发送POST请求,然后将响应返回到HTML页面。

示例:

视图

def process_like(request):
    post_id = request.POST['post_id']
    post = Post.objects.get(id=post_id)
    post.process_likes()
    return JsonResponse({"message": "Success"})

网址

urlpatterns = [
    ...
    path('process_like/', views.process_like, name="process_like")
    ...
]

html / js

<div class="post" data-post-id="{{post.id}}">this is the post</div>

<script>
var posts = document.querySelectorAll('.post')

posts.forEach(post => {
    post.addEventListener('click', e => {
        e.preventDefault()
        var post_id = post.getAttribute('data-post-id')
        var config = {
          method: "POST",
          body: {post_id: post_id}
          headers: {
              "X-CSRFToken": "{{ csrf_token }}",
              "Accept": "application/json",
              "Content-Type": "application/json"
          },
        }

        fetch('{% url "process_like" %}', config)
        .then(response => response.json())
        .then(data => console.log(data))
    })
})
</script>

或者如果您使用jQuery

<script>
$('.post').on('click', function (e) {
    e.preventDefault();
    var $this = $(this);
    var post_id = $this.data('post-id');

    $.ajax({
        method: "post",
        url: "{% url 'process_like' %}",
        data: {csrfmiddlewaretoken: "{{ csrf_token }}", post_id: post_id}
    }).done(function (response) {
        console.log(response)
    })
})
</script>