3

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
Chirag Sharma
  • 77
  • 1
  • 10
  • here is a link hope can help you. https://stackoverflow.com/questions/24229397/django-object-is-not-json-serializable-error-after-upgrading-django-to-1-6-5 – mino Apr 10 '19 at 10:57

1 Answers1

2

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.

ruddra
  • 50,746
  • 7
  • 78
  • 101
  • I wanted to ask one more thing that the query is returning every user in the database and not the just specific user that starts with **q** keyword.Am I doing something wrong with the queryset ? – Chirag Sharma Apr 10 '19 at 12:20
  • 1
    Actually got it **term** was the query input and i was using **search** as the keyword. – Chirag Sharma Apr 10 '19 at 12:51