Reputation:
Hello guys i want to populate a dropdown with the ids from the database, but when iterating over the list i get back also the brackets and the commas and some spaces.
In views.py, i have the following:
id = list(Device.objects.values_list('patientId', flat=True).distinct())
print(id)
for item in id:
print(item)
context = {"filename": filename,
"collapse": "",
"patientId": json.dumps(id),
"labels": json.dumps(labels, default=str),
"data": json.dumps(data),
}
The print is returning exactly what i want the ids(1,2,3), but when going in the frontend(index.html), with the following code:
{{patientId}}
<div class="row">
<label for="patientId">Choose a patient:</label>
<select name="patient" id="patient">
{% for item in patientId%}
<option value="{{item}}">
{{item}}
</option>
{%endfor%}
</select>
How can i get in the frontend the dropdown with the correct values?
Upvotes: 0
Views: 587
Reputation: 1875
your problem is that you dont pass a list
to the django template, instead you are passing a str
(string representation of list -> json)
context = {"filename": filename,
"collapse": "",
"patientId": json.dumps(id), # < -----------------------
"labels": json.dumps(labels, default=str),
"data": json.dumps(data),
}
that line should be
"patientId": id # this should be a better and more specific name
because you need to pass a list to the template in order to iterate over it like this
{% for item in patientId%}
and btw, you templates should look like this
{% for item in patientId %} # notice the space
{% endfor %} # notice the spaces
Upvotes: 1