Django cannot convert queryset to list to js array

Using Django I have a view which pulls a queryset and attempting to convert to a list as context to the template which then feeds through to javascript array however it's as if the queryset is not converting to a real list as javascript validation is not accepting the list and thus validation not working.

I have also created a normal list rather than from a queryset and works as I expect for my JS validation but everything I have tried in converting the queryset to a list the javascript just will not accept it to the array.

I have also tried to convert the list as json as well from what I read online and still not working.

I have tried my own for loop on the queryset to append to a new list but also done nothing.

Please see the following code:

View (manual python list which works tried and tested)

mylist= ['sid', 'john']
context = {"mylist": mylist}

View (first attempt at converting queryset to list)

test = User.objects.values_list('username', flat=True)
mylist = list(test)
context = {"mylist": mylist}

View (second attempt at converting queryset to list to json)

test = User.objects.values_list('username', flat=True)
mylist= json.dumps(list(test))
context = {"mylist": mylist}

Template(with javascript)

let listNames = {{mylist|safe}};

  if ( listNames.includes(x.toLowerCase()) ) {
    text = x + ' allready taken.';
  }

What am I doing wrong in converting the queryset to a list for the javascript array to accept in the template?

Help is much appreciated. Thanks

Change you views.py.

test = list(User.objects.filter(column_name='Value you want to fetch').values())
context = json.dumps({"mylist":test})
return render(request, "your JS location", context})

Use escapejs in your Javascript

let listNames = {{mylist|escapejs}};

Back to Top