[英]How to run a method inside a Model when a JavaScript actionListener is triggered?
I have the next Model: 我有下一个模型:
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
What I want to do is when a icon in a template is clicked, I want the process_likes method to be run, this method is going to increment by one the value of likes. 我想做的是单击模板中的一个图标时,我要运行process_likes方法,该方法将点赞的值增加1。 My script looks like this:
我的脚本如下所示:
<script>
let corazon = document.querySelector('.icon-heart-empty');
corazon.addEventListener('click', ()=>{
corazon.classList.toggle('icon-heart');
});
</script>
Here I toggle the class of my icon to show if is clicked or uncliked, but how can I call the process_like method using pure JavaScript? 在这里,我切换图标的类以显示是否单击或不喜欢,但是如何使用纯JavaScript调用process_like方法呢?
You would need to use an AJAX
call to send a POST
request to your server, and then return a response to your HTML page. 您将需要使用
AJAX
调用将POST
请求发送到服务器,然后将响应返回到HTML页面。
Example: 例:
view 视图
def process_like(request):
post_id = request.POST['post_id']
post = Post.objects.get(id=post_id)
post.process_likes()
return JsonResponse({"message": "Success"})
urls 网址
urlpatterns = [
...
path('process_like/', views.process_like, name="process_like")
...
]
html/js 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>
Or if you use jQuery 或者,如果您使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.