拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 使用串列的Len创建DjangoHTML页面?

使用串列的Len创建DjangoHTML页面?

白鹭 - 2022-03-07 1946 0 0

我知道这之前必须被问过,我似乎无法找出正确的术语来搜索以找到它被称为什么或如何去做。我有一个动态表,一天可能有 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 物件,然后遍历它们以创建所有链接。

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *