我有一个API,它给了我json数据。我希望从json和list中获取一些值作为HTML的下拉列表。我需要为此创建表单吗?
例如,我有一个URL http://netbox.com/api/deviceroles,它提供了一个json文件,我想从中提取名称。 deviceroles将包含所有名称的值。
views.py
import json, urlib
def home(request):
if request.method == 'GET'
url = "http://netbox.com/deviceroles"
response = urllib.urlopen(url)
data = json.loads(response.read())
for i in range (0, len (data['results'])):
deviceroles = data['results'][i]['name']
return render(request,"base.html")
base.html文件
<div class="em-c-field">
<label for="file" class="em-c-field__label">Device Role</label>
<div class="em-c-field__body">
<select class="em-c-select em-c-select" id="file" placeholder="Placeholder">
<optgroup>
<option value="" disabled="disabled" selected="selected">please select a device role</option>
</optgroup>
</select>
</div>
答案 0 :(得分:0)
如果你正在使用Django的内置模板,你可以这样做:
repository
views.py到
<select class="em-c-select em-c-select" id="file" placeholder="Placeholder">]
{% for devicerole in deviceroles %}
<optgroup>
<option value="{{ devicerole }}" disabled="disabled" selected="selected">{{ devicerole }}</option>
</optgroup>
{% endfor %}
</select>