How to run a method inside a Model when a JavaScript actionListener is triggered?

General Tech Bugs & Fixes 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

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. 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?

profilepic.png
manpreet 2 years ago

 

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.

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

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

<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

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

    $.ajax
                                                    
                                                    
0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.