The error message received is: "TypeError: Unable to serialize method object to JSON."

Every time I click on the like button, an internal server error shows up in the console.

The issue lies in returning a HttpResponse from the view function. How can I properly return a value in HttpResponse so that I can access it in JavaScript?

Console error:

jquery.js:9837 POST 500 (Internal Server Error)

Views :

    class PostLikeView(generic.View):
        def post(self, request, *args, **kwargs):
            user = request.user
            post_id = request.POST['post_id']
            post = Post.objects.get(id=post_id)
            user_liked, created = PostLike.objects.get_or_create(post=post, user=user)
            if not created:
                PostLike.objects.filter(post=post).filter(user=user).delete()
                total = post.like.count
                data = {'total-like':total,'user_liked':False}
            else :
                total = post.like.count
                data = {'total-like':total,'user_liked':True}
            return HttpResponse(json.dumps(data), content_type='application/json')
            

javaScripts :

    <script type="text/javascript"> 
        $('.likebutton').click(function(){ 
        var id; 
        id = $(this).attr("data-catid"); 
        $.ajax( 
        { 
            type:"POST", 
            url: "blogs/post/like/", 
            data:{ csrfmiddlewaretoken: "{{ csrf_token }}",
                     post_id: id 
                 },
            dataType: 'json', 
          });
          //(function(data){
            //data = JSON.parse(data)
            //console.log(data)
         // });
           });
        </script>  

Errors received in terminal :

    Internal Server Error: /blogs/post/like/
    Traceback (most recent call last):
      File "C:\publish\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\publish\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\publish\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "C:\publish\lib\site-packages\django\views\generic\base.py", line 71, in view
        return self.dispatch(request, *args, **kwargs)
      File "C:\publish\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
        return handler(request, *args, **kwargs)
      File "C:\publish\studentcollegeworld\blogs\views.py", line 114, in post
        return HttpResponse(json.dumps(data), content_type='application/json')
      File "c:\users\abc\appdata\local\programs\python\python38\lib\json\__init__.py", line 231, in dumps
        return _default_encoder.encode(obj)
      File "c:\users\abc\appdata\local\programs\python\python38\lib\json\encoder.py", line 199, in encode
        chunks = self.iterencode(o, _one_shot=True)
      File "c:\users\abc\appdata\local\programs\python\python38\lib\json\encoder.py", line 257, in iterencode
        return _iterencode(o, 0)
      File "c:\users\abc\appdata\local\programs\python\python38\lib\json\encoder.py", line 179, in default
        raise TypeError(f'Object of type {o.__class__.__name__} '
    TypeError: Object of type method is not JSON serializable
    [25/May/2020 17:14:55] "POST /blogs/post/like/ HTTP/1.1" 500 20260

Answer №1

To enhance the code, consider adding a closing parenthesis after post.like.count in both instances.
The correct syntax to use is total = post.like.count() within the if and else statements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to display a custom image as a check mark on a checkbox

I tried to add some custom CSS to style the images on my checkmark boxes. The goal was to display an image with a checkmark when clicked, but unfortunately, it's not working as expected during testing. For this task, I utilized CSS and HTML from a he ...

Is it possible for Angular to retrieve information from one JSON file but not another?

After updating the names in the code to reflect the current ones, I would greatly appreciate any help or suggestions! The json file has been provided, so there's not much additional setup required. Just a heads up: I haven't created a service fi ...

The animation function occasionally halts unexpectedly at a varying position

I am facing an issue with an animation function that I have created to animate a list of images. The function takes in parameters such as frames per second, the stopping point, and the list element containing all the images. However, the animation stops un ...

Speaking about the `this` Vue component in an event listener context

Consider this Vue component that is equipped with a global event listener: let myApp = new Vue({ data: { foo: 0; }, methods: { handle: function(event) { this.foo = 1; // 'this' pertains to the handler, not ...

Challenges associated with integrating PayPal server

I'm encountering issues with a web project I'm developing. The payment functionality is working fine, but the problem lies in just one line of code. I am attempting to store the names of purchased products (courses, in this case) in a billing sys ...

ExpressJS exhibits unique behavior based on whether the API is requested with or without the specified PORT number

I have encountered an issue with my 2 flutter web apps. One of them is functioning flawlessly when I request the URL, but the other one only works when I include the port xxxxx:4000/nexus-vote. However, when I remove the port, I receive a status code of 20 ...

The proxy encountered a TypeError when the trap for the property 'set' returned a falsish value

After migrating my code from using es5 class prototype representation to es6 class representation, I encountered an error. This is the comparison of the code before and after migration: ES5 syntax function RoutingScreen (context) { Object.assign(this, ...

Entity Framework and the GET request error: Connection Reset

Currently, I am working on developing a straightforward notes application using Entity Framework in ASP.Net Core for the backend and AngularJS for the frontend. The main objective is to have the app load a pre-existing list of notes from my MySQL database ...

What is the best way to change data into an array using Java script?

In this code snippet, I am utilizing a loop to send data to an ajax function in JSON format: foreach($careers->getItems() as $item){ if($item->getDepartment()==$departmentID && $item->getLocation()==$location ...

Want to easily switch between pictures in the Gallery?

I've created a gallery using jQuery, CSS & HTML and now I want to implement next and previous image buttons. I have added the buttons to the page and written functions for them, but I am struggling with the implementation. Here is my code, if anyone h ...

Leveraging React Hooks' useEffect to trigger a prop callback function defined with useCallback

Currently, I am working on developing a versatile infinite scrolling feature using React Hooks along with the ResearchGate React Intersection Observer. The main concept revolves around a parent passing down a mapped JSX array of data and a callback functio ...

Issue with dropdown element not triggering JavaScript onchange event

I am in the process of developing an application that involves searching a database and enabling users to compare the results. To achieve this, I require multiple dependent drop-down menus. While I have some understanding of HTML and PHP, my coding experti ...

deciphering JSON objects based on specific keys

Struggling to complete a seemingly straightforward task has left me feeling frustrated. In the header of my HTML page, I have an external car dealer API being called. At the bottom of the page, there is another external .js file containing a series of if- ...

How can I retrieve Feature Information exclusively from the currently visible WMS layers in OpenLayers 3?

I am working with an Openlayers map that features multiple WMS layers. I am trying to use the "getGetFeatureInfoUrl" function to request feature information, but only for the layers that are currently visible on the map. Additionally, if there are multiple ...

Can you customize the buttons in the operation panel of an antd image preview window?

https://i.sstatic.net/hZLOn.png I am looking to add a button that allows users to download or share the image being previewed. Is there a way to achieve this functionality? I have researched and read through the documentation but have not found a solutio ...

Encountering difficulties while integrating django-tables2 into project

Currently, I am in the process of integrating django-tables2 into a project and I am following the guidelines provided here: I am diligently following the steps outlined below: Execute the command: pip install django-tables2 Include 'django_tables2 ...

Exploring the World of Github on Windows: Understanding the 'master' and 'gh-pages' Branches

I have developed a simple jQuery plugin and uploaded it to Github. I am using both the Github website and Github for Windows to manage this project. However, when I try to include the .js or .css files from Github using the Raw links, my browser fails due ...

Utilizing Django to Retrieve HTML LIST Data Seamlessly Without Forms or Models

After creating an HTML page containing a series of list items, I wanted to implement a feature where clicking a button would read the data within the list and perform a transformation. I came across an example similar to this on Stack Overflow. However, t ...

Progressive JQuery Ajax Requests

I'm attempting to retrieve specific information from a webpage, such as the title of the page and the domain name, and then perform an asynchronous POST request using jQuery with that extracted data. However, I've encountered an issue where my Ja ...

I would like to inquire about the process of accessing profile information on a website through the LinkedIn API

Do you know how I can use the latest LinkedIn JavaScript API with OAuth 2.0 to retrieve my own profile details for a website? The goal is to automatically update the website using my linked profile information. I have attempted the following: api_key: ...