Django 用值填充下拉列表

Django populating dropdown with values

大家好,我想用数据库中的 ID 填充下拉列表,但是在遍历列表时,我还返回了括号、逗号和一些空格。

在 views.py 中,我有以下内容:

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),
           }

打印返回的正是我想要的 ids(1,2,3),但是当进入前端时 (index.html),使用以下代码:

{{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>

What i get

我怎样才能在前端下拉菜单中获得正确的值?

你的问题是你没有将 list 传递给 django 模板,而是传递了 str (列表的字符串表示 -> json)

context = {"filename": filename,
           "collapse": "",
           "patientId": json.dumps(id), # < -----------------------
           "labels": json.dumps(labels, default=str),
           "data": json.dumps(data),
           }

那一行应该是

   "patientId": id # this should be a better and more specific name

因为您需要将列表传递给模板以便像这样对其进行迭代

{% for item in patientId%}

顺便说一句,你的模板应该是这样的

{% for item in patientId %} # notice the space
{% endfor %} # notice the spaces