我知道這之前必須被問過,我似乎無法找出正確的術語來搜索以找到它被稱為什么或如何去做。我有一個動態表,一天可能有 5 個專案,接下來的 10 個專案(從資料庫中提取),我將在表中創建超鏈接,然后打開另一個專門關于該串列物件的 HTML 頁面。我似乎無法弄清楚如何使這項作業?我現在使用 Django 的方式是我為每個特定頁面創建一個 HTML 檔案和 URL 視圖,但是如果我有一天想創建 3,第二天想創建 5,我該怎么做,現在我的想法可以 不了解如何僅使用一個模板為串列中的每個事物動態創建該 HTML 檔案?只是想找人告訴我這叫什么,或者我可以在 Django 檔案中搜索什么來查找示例?初步回答后編輯
這是我的應用程式 URL 檔案:
網址
urlpatterns = [
# The home page
#path('', views.index, name='home'),
# Matches any html file
#path('charttest/', views.charttest, name='charts'),
path('', views.nba, name='nba'),
path('nbav2/', views.nba2, name='nba2'),
path('nbav3/', views.nba3, name='nba3'),
path('ncaa/', views.ncaa, name='ncaa'),
path('nhl/', views.nhl, name='nhl'),
path('testing/', views.current_game_table, name='testing'),
path('your_details_view/<str:pk>', views.your_details_view, name='your_details_view')
}
這是我的視圖檔案:
def current_game_table(request):
items = Nbav8.objects.using('totals').all()
# rest of your code
return render(request, 'home/testing.html', {'items': items})
def your_details_view(request, pk):
item = Nbav8.objects.using('totals').get(pk=pk)
return render(request, 'home/chart-chartjs5.html', {'item': item})
current_day_home_team = list(Nbav8.objects.using('totals').values_list('home_team_field', flat=True))
current_day_away_team = list(Nbav8.objects.using('totals').values_list('away_team_field', flat=True))
awayuyu = []
homeuyu = []
for team in current_day_home_team:
home_team_list1 = PreviousLossesNbav1WithDateAgg.objects.using('totals').filter(Q(away_team_field=team) | Q(home_team_field=team)).values_list('actual_over_under_result_field', flat=True)
homeuyu.append(list(home_team_list1[:5]))
home_team_list2 = homeuyu
for team in current_day_away_team:
away_team_list1 = PreviousLossesNbav1WithDateAgg.objects.using('totals').filter(Q(away_team_field=team) | Q(home_team_field=team)).values_list('actual_over_under_result_field', flat=True)
awayuyu.append(list(away_team_list1[:5]))
away_team_list2 = awayuyu
這是根 URL 檔案:
# -*- encoding: utf-8 -*-
"""
"""
from django.contrib import admin
from django.urls import path, include # add this
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("apps.authentication.urls")),
path("", include("apps.home.urls")),
]
這是我的 testing.html
Hello World
{{ items }}
{% for item in items %}
<a href="{% url for 'your_details_view' item.pk %}">{{ item }}</a>
{% endfor %}
每次我嘗試導航到我的網頁/測驗時,我都會收到錯誤訊息“找不到''的反向。''不是有效的視圖函式或模式名稱。”
追溯:
Environment:
Request Method: GET
Request URL: https://www.total-scores.com/testing/
Django Version: 3.2.6
Python Version: 3.9.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.home']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /home/jbarth200/priv-django-dashboard-gradient-pro-master/apps/templates/home/testing.html, error at line 6
Reverse for '' not found. '' is not a valid view function or pattern name.
1 : Hello World
2 :
3 : {{ items }}
4 :
5 : {% for item in items %}
6 : <a href=" {% url for 'your_details_view' item.pk %} ">{{ item }}</a>
7 : {% endfor %}
Traceback (most recent call last):
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/./apps/home/views.py", line 1739, in current_game_table
return render(request, 'home/testing.html', {'items': items})
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/template/base.py", line 170, in render
return self._render(context)
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/template/defaulttags.py", line 211, in render
nodelist.append(node.render_annotated(context))
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/template/defaulttags.py", line 446, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/urls/base.py", line 86, in reverse
return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
File "/home/jbarth200/priv-django-dashboard-gradient-pro-master/env/lib/python3.9/site-packages/django/urls/resolvers.py", line 694, in _reverse_with_prefix
raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /testing/
Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name.
模型檔案:
class Nbav8(models.Model):
home_team_field = models.TextField(db_column='HOME TEAM:', blank=True, null=True, primary_key=True) # Field name made lowercase. Field renamed to remove unsuitable characters. Field renamed because it ended with '_'.
away_team_field = models.TextField(db_column='AWAY TEAM:', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. Field renamed because it ended with '_'.
projected_points_field = models.FloatField(db_column='PROJECTED POINTS:', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. Field renamed because it ended with '_'.
home_injury = models.TextField(db_column='Home Injury', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters.
away_injury = models.TextField(db_column='Away Injury', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters.
game_points_with_formula_field = models.BigIntegerField(db_column='GAME POINTS WITH FORMULA:', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. Field renamed because it ended with '_'.
game_money_line_field = models.FloatField(db_column='GAME MONEY LINE:', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. Field renamed because it ended with '_'.
over_or_under = models.TextField(db_column='OVER OR UNDER', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters.
class Meta:
managed = False
db_table = 'nbav8'
uj5u.com熱心網友回復:
我認為您想要的稱為詳細資訊頁面。我將呼叫模型專案。您可以通過在 urls.py 上執行以下操作輕松為每個專案創建詳細視圖:
# urls.py
urlpatterns = [
...
path('your_details_view/<int:pk>', views.your_details_view, name='your_details_view'),
# or if your primary key is NOT an integer:
path('your_details_view/<str:pk>', views.your_details_view, name='your_details_view'),
...
]
您的根 urls.py 看起來與我習慣的不同。也許是正確的,但試試這個。洗掉app部分,像這樣:
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("authentication.urls")),
path("", include("home.urls")),
]
那么你的看法如下:
# views.py
# view of the page with all the links:
def your_dynamic_table_view(request):
items = Item.objects.all()
# rest of your code
return render(request, 'your_app/dynamic_table.html', {'items': items})
# view for the details page
def your_details_view(request, pk):
# your code
# Here is where you will get the particular item based
# on the pk that was in the <a href> link
item = Item.objects.get(pk=pk)
return render(request, 'your_app/detail_view.html', {'item': item})
現在,在您的表格中,您可以簡單地通過遍歷它們來放置指向所有專案的鏈接;在你的 dynamic_table.html 中是這樣的:
動態視圖.html:
{% for item in items %}
<a href="{% url 'your_details_view' item.pk %}">{{ item }}</a>
{% endfor %}
現在鏈接將轉到your_details_view,這將呈現一個特定于該專案的 pk 的 html 頁面。(它不必是 pk,甚至是整數)。href 錨標記中的item.pk,因此當您單擊它時,它將轉到your_details_view,這將呈現一個 html 頁面,.../your_details_view/45例如,其中 45 是我為特定專案制作的 pk。pk然后可以在您的 detail_view.html 頁面中使用該變數(特定專案的主鍵)以及任何專案的欄位:
detail_view.html:
Here you have access to the all of the fields
of the particular item, say item with pk=45, if
that is pk in the <a href> tag. For example if the
item has a field called price, then you can do:
<p>The price of this item is: {{ item.price }}</p>
注意我只是編了名稱專案。例如,如果你有一個你呼叫的模型Item,那么在你將擁有所有鏈接(不是詳細資訊頁面)的模板中,你可以傳遞所有 Item 物件,然后遍歷它們以創建所有鏈接。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/416261.html
標籤:
