Vinand Vinand - 16 days ago 4
Ajax Question

Internal error on AJAX call to a Django view (restframework endpoint)

jQUERY:

$.ajax({
url: '/notify/',
type:'GET',
dataType: 'json',
success: function (data) {
if (data.is_taken) {
alert("A user with this username already exists.");
}
}
});


urls.py:

url(r'^notify/$', views.notify,name='notify'),


views.py:

from django.http import HttpResponse
from django.http import Http404
from django.http import JsonResponse

def notify(request):
data = {
'is_taken': Notification.objects.all()
}
return JsonResponse(data)


On calling ajax in console:

Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR)


What may be wrong? Everything is correct and present . Django 1.8 , jQuery 3.1.0

EDIT: Django error log traceback

Internal Server Error: /notify/
Traceback (most recent call last):
File "/Users/TheKotik/djboy/denv/lib/python3.5/site-packages/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/TheKotik/djboy/blog/views.py", line 212, in notify
return JsonResponse(data)
File "/Users/TheKotik/djboy/denv/lib/python3.5/site-packages/django/http/response.py", line 535, in __init__
data = json.dumps(data, cls=encoder)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "/Users/TheKotik/djboy/denv/lib/python3.5/site-packages/django/core/serializers/json.py", line 112, in default
return super(DjangoJSONEncoder, self).default(o)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: [<Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>, <Notification: Notification object>] is not JSON serializable

Answer

You need to be sure your result (in your case data) is json serializable, note you are doing 'is_taking': Notification.objects.all(), you should do something like this instead:

from rest_framework.response import Response
from rest_framework.decorators import api_view

@api_view(['GET', ]) 
def notify(request):
    data = {
        'is_taken': NotificationSerializer(Notification.objects.all(), many=True).data
    }
    return Response(data)

And write the Serializer e.g. NotificationSerializer for Notification