我有一個回傳HTML responseusing的視圖render。回傳的資料特定于模板。
如果我想在另一個頁面上使用該資料,我應該用相同的邏輯撰寫另一個視圖,還是有辦法將資料從視圖 1 傳遞到視圖 2
看法
return render(request, 'pages/project_details.html', {"project": project,
網址
path('show_project_details/<project_id>', view=show_project_details, name="show_project_details"),
我知道 aview只是一個函式,它接受一個請求并用它做一些事情,但我不明白如何向模板中的視圖發出請求并在現有頁面中使用回應。
這里的例子:
## filename: views.py
from django.shortcuts import render
from .models import Team
def index(request):
list_teams = Team.objects.filter(team_level__exact="U09")
context = {'youngest_teams': list_teams}
return render(request, '/best/index.html', context)
我想將其中的資料回傳context到home.html和index.html。
希望這是有道理的?
uj5u.com熱心網友回復:
您可以使用urls.py通過 URL 表示法傳遞變數。
例如 -獲取團隊資訊:
模板
{% for team in youngest_teams %}
<a href="{% url 'get_team_info' team.id %}">Team</a>
{% endfor %}
網址.py
path('team_info/<team_id>', view=team_info, name="get_team_info")
視圖.py
def team_info(request, team_id=None):
team = Team.objects.get(id=team_id) #Information on team is passed.
uj5u.com熱心網友回復:
您的情況有多種情況。讓我一一解釋它們。假設您有兩個模板。一個是模板1,另一個是模板2。
- 如果您想對模板 1 和模板 2 使用相同的邏輯。您可以在 views.py 和 url.py 中使用一個變數,并在該變數上使用一個條件,在您的情況下是 team_id。例如
def index(request, team_id):
list_teams = Team.objects.filter(team_level__exact="U09")
context = {'youngest_teams': list_teams}
if team_id == 1:
return render(request, '/best/index.html', context)
elif: team_id == 2:
return render(request, '/best/template2.html', context)
在 urls.py 中,你可以這樣寫:
path('team_info/<int:team_id>', view=team_info, name="get_team_info")
- 如果您不想在視圖和 URL 中使用該變數。然后你可以在views.py中用相同的代碼撰寫不同的視圖。但是在多個id的情況下,會造成代碼重復。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/400929.html
標籤:姜戈
上一篇:如何在django自定義用戶模型中將username欄位更改為user_name?
下一篇:即使它是一個類,為什么AttributeError:'function'objecthasnoattribute'as_view'
