Chirag Sharma
Chirag Sharma

Reputation: 77

Object of type User is not JSON serializable

I am creating a an auto complete search for my web page and where I am trying to fetch name of users from database using ajax calls.

My AJAX call is running fine and going to designated URL.

I have tried using JSON encoder but that also did not work.

I am a bit new to DJANGO.Please help

My views.py

def autocomplete(request):
if request.is_ajax():
    q = request.GET.get('search', '').capitalize()
    search_qs = Profile.objects.filter(user__username__startswith=q)
    results = []
    print (q)
    for r in search_qs:
        results.append(r.user)
    data= json.dumps(list(results), cls=DjangoJSONEncoder)
else:
    data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)

My models.py

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')

def __str__(self):
    return f'{self.user.username} Profile'

Error I am getting

TypeError: Object of type User is not JSON serializable
[] "GET /ajax_calls/search/?**term=he** HTTP/1.1" 500 15860

Upvotes: 3

Views: 10019

Answers (1)

ruddra
ruddra

Reputation: 52028

I don't know why you are querying through Profile, where you can query directly through User. I think the proper implementation should be like this:

from django.core.serializers import serialize 

users = User.objects.filter(username__startswith=q)

str_data = serialize('json', users, cls=DjangoJSONEncoder). # Or you don't need to provide the `cls` here because by default cls is DjangoJSONEncoder

data = json.loads(str_data)

Documentation can be found here.

Upvotes: 2

Related Questions