[英]How to access(loop through) queryset passed from views to html template inside javascript block in django?
[英]How to send QuerySet from HTML template to views via urldispatcher in django
我正在嘗試通過 urldispatcher 將 QuerySet 從 index.html 發送到視圖。 我搜索了文檔,但主要有關於 int:id、path:kjf 等的信息。有一些關於關鍵字 args 的信息,但我對它們了解不多。 我是 Django 的初學者,這是我的第一個項目,而且這個項目的截止日期也快到了,所以任何幫助都會很明顯。
索引.html
只列出必要的代碼...
{% if datadict and datadict != "Sorry no data found" %}
{% for item in datadict %}
<tr>
<th width="5%" scope="row"><a href="{% url 'index' datadict %}" class="btn btn-secondary">Generate</a></th>
<td>{{ item.title }}<td>
</tr>
{% endfor %}
{% endif %}
網址.py
urlpatterns = [
path('', views.index, name='index'),
path('<datadict>', views.index, name='index')
]
視圖.py
def index(request, datadict=None):
if (datadict):
b = datadict[0] ### this is just testing to see if i am receiving the data in QuerySet from or not
return render(request, 'dapp/index.html', {'b': b})
datadict 有這個數據:-
<QuerySet [{'id': 1002, 'year': '2000', 'sector': 'test', 'topic': 'test1', 'insight': 'dont no', 'url': 'localhost' , 'start': '2000', 'impact': 'impaca', 'added': 'January 08 2001', 'published': 'August 03 2001', 'relevance': '4', 'pest': ' test2', 'source': 'CBSE', 'title': '添加測試數據', 'like': '5'}]>
我不確定你想要達到什么目的,如果我很好地理解你的問題,你希望能夠訪問這樣的 URL: /[{'id': 1002, 'year': '2000.../
然后獲取一個加載 URL 中數據的頁面。 這可能不是一個好主意,因為 QuerySets 不應該放在 URL 中。 這是可能的,但您必須將其轉換為字符串,然后解析該字符串,如下所示:
網址.py
urlpatterns = [
path('<str:datastr>', views.index, name='index')
]
視圖.py
import json
def index(request, datastr=None):
if (datastr):
datastr = datastr.replace('\'', '"') # This is needed because json.loads expects keys and values to be inside double quotes
datadict = json.loads(datastr)
return render(request, 'dapp/index.html', {'datadict': datadict})
然后您可以使用 url /[{'id': 1002, 'year': '2000'...}]/ 訪問該頁面
這應該可行,但實際上不是最佳的。 如果數據中有引號,它們將被打破,並且所有內容都是字符串,甚至是數字。
這是更常見的事情:如果數據實際上在 django 可以訪問的數據庫中,最好在視圖中檢索它。 例如,要通過 id 獲取對象,您可以這樣做:
網址.py
urlpatterns = [
path('<int:id>', views.index, name='index')
]
視圖.py
def index(request, id=None):
data = None
if id:
# Get data here.
# For example: data = models.ModelName.objects.get(id=id)
return render(request, 'dapp/index.html', {'datadict': data})
或者,如果您確實希望客戶端將數據發送到將要呈現的服務器,則最好使用 GET 參數或使用 POST 請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.