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