본문 바로가기

Python/Django

[Error solved][Django+Ajax] method object is not JSON serializable 에러

에러 내용

C:\Users\jisun\dev\python\django\djangogirls_video\video\views.py changed, reloading.
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
April 22, 2020 - 19:55:04
Django version 3.0.5, using settings 'djangotube.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[22/Apr/2020 19:55:07] "GET /video/1 HTTP/1.1" 200 3518
Internal Server Error: /video/like/
Traceback (most recent call last):
  File "C:\Users\jisun\dev\python\django\djangogirls_video\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\jisun\dev\python\django\djangogirls_video\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\jisun\dev\python\django\djangogirls_video\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\jisun\dev\python\django\djangogirls_video\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\jisun\dev\python\django\djangogirls_video\venv\lib\site-packages\django\views\decorators\http.py", line 40, in inner
    return func(request, *args, **kwargs)
  File "C:\Users\jisun\dev\python\django\djangogirls_video\video\views.py", line 83, in video_like
    return HttpResponse(json.dumps(context), content_type="application/json")
  File "C:\Python\Python38-32\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python\Python38-32\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python\Python38-32\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Python\Python38-32\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

 

문제 분석

models.py

class Video(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    video_key = models.CharField(max_length=12)
    likes_user = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='likes_user')

    def count_likes_user(self):
        return self.likes_user.count()

    def __str__(self):
        return self.title

views.py

@login_required
@require_POST
def video_like(request):
    pk = request.POST.get('pk', None)
    video = get_object_or_404(Video, pk=pk)
    user = request.user

    if video.likes_user.filter(id=user.id).exists():
        video.likes_user.remove(user)
        message = '좋아요 취소'
    else:
        video.likes_user.add(user)
        message = '좋아요'

    context = {'likes_count':video.count_likes_user, 'message': message}
    return HttpResponse(json.dumps(context), content_type="application/json")

 

문제 해결

video_like view에서 Video modelcount_likes_user functionjson으로 변환시키는 과정에 문제가 있었다.

왜냐하면, function 그 자체는 json으로 변환될 수 없기 때문에,

function을 call해야 하기 때문이다.

즉,

video.count_likes_user => video.count_likes_user()

이렇게 간단히 해결할 수 있었다.

 

https://stackoverflow.com/questions/48008184/method-object-is-not-json-serializable

 

method object is not JSON serializable

I am using ajax to refresh the cart items when cart item is removed. It works well, if i don't response object with image otherwise I get an error method object is not JSON serializable. If i use

stackoverflow.com