我正在學習如何在 Django 中處理 JSON 檔案,并且我已經成功解壓縮了 JSON,但現在我想把它放在表中。
有沒有辦法使用純 HTML 并使用所謂的“龍卷風括號”{{ }} 而不是 jQuery / JS 函式?
我的代碼:
API 后端檔案
from requests import get
default_values = {
"repoName": "",
"repoURL": ""
}
def get_response():
response = get_json()
main_dictionary = {
"items":[]
}
try:
for repos in response:
main_dictionary["items"].append({
"repoName": repos["name"],
"repoURL": repos["html_url"]
})
except KeyError as error:
print("Key Error, check the validity of the keys you try to use to decode JSON")
return main_dictionary["items"]
def get_json():
first_response = get('https://api.github.com/users/jacobtoye/repos')
response = first_response.json()
return response
渲染純 HTML 表格的嘗試失敗
{% block content %}
<table>
<tr>
{% for repos in response %}
<td>{{ repoName }}</td>
{% if not forloop.last and forloop.counter == 3 or forloop.counter == 6 %}
</tr>
{% endif %}
<tr>
{% endfor %}
</tr>
</table>
該表根本不顯示。我不認為任何其他代碼檔案對于這個問題來說很重要,但是如果你認為你需要更多代碼,我很樂意向你展示 LMK :)
uj5u.com熱心網友回復:
在 Django 的視圖中,您通常傳遞諸如context.
基于函式的視圖:
def a_view(request):
context = {
'some_things': Thing.objects.all()
}
return render(request, 'your_template.html', context)
基于類的視圖:
class TheView(View):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['some_things'] = Thing.objects.all()
return context
使用模板中的任何給定方法,它將像這樣作業:
{% for thing in some_things %}
{{ thing }}, {{ thing.id }}, {{ thing.get_related_things }}
{% endfor %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488854.html
上一篇:我可以從用戶那里獲取字串,如果它的定義在字典中,在python中列印定義?
下一篇:正則運算式保留字串中的特定單詞
