0

UPDATE 7/23/2020

I have a Django project where I am trying to pass a list of values from a python function to my 'index.html' file. This list of values comes from a DB query in my views.py file

my views.py

def index_view(request):
    
    context = {}


    con=sqlite3.connect("db.sqlite3")
    cursor=con.cursor()

    db_query="SELECT distinct product_name from dboinvproduct"

    cursor.execute(db_query)

    result=cursor.fetchall()

    con.close()

    list_of_products = list(itertools.chain(*result)) 
    
    context['product_names'] = list_of_products
    return render(request, 'index.html', context)

then within the body of my index.html

function loadFunct(){
               var products = "{{product_names|safe}}";
               alert(products);
              }

And the alert shows the following string:

['product a', 'product b', 'product c', 'product d']

Which is much closer than I was previously. The problem is, this is a string that looks like an array... Which means this will not work for my application... I need it to be in the form of an array.

What is the best way to do this? I have read about json_dumps on the python side, but I get a typeError because that expects a dictionary...

0

1 Answer 1

1

json.dumps() should accept list like this.

>>> import json
>>> json.dumps(['a','b'])
'["a", "b"]'

Therefore you can pre-jsonify the list in the view like this,

context['product_names'] = json.dumps(list_of_products)
return render(request, 'index.html', context)

and use in the template like this.

function loadFunct(){
    var products = {{product_names|safe}}; // Be aware that there are no quotes or double quotes. 
    console.log(products);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks user3003464, that worked! This feature is now fully functional. Very pleased!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.