Home > Enterprise >  Using Primary Key To Index HTML Template Django
Using Primary Key To Index HTML Template Django

Time:01-26

Bit confused on how I would index a list I have based on the primary key in the HTML template? Here is my views page:

def current_game_table(request):
    items = list(Nbav8.objects.using('totals').all())
    return render(request, 'home/testing.html', {'items': items})

def current_games(request, pk):

    item = Nbav8.objects.using('totals').get(pk=pk)
    items2 = list(CurrentDayStats.objects.using('totals').values_list('home_team_over_under_field', flat=True))
    return render(request, 'home/testing2.html', {'item': item, 'uuup':items2})

Here is my testing1.html:

Hello World

{{ items }}

{% for item in items %}
        <a href="{% url 'current_games' item.pk %}">{{ item.home_team_field }}</a>
{% endfor %}

Here is my testing2.html:

<p>The price of this item is: {{ item }}</p>


Where is it?!!?

{{ item.uuup }}

URL file:

from django.urls import path, re_path
from apps.home import views

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('current_games/<int:pk>', views.current_games, name='current_games')

My pages display fine testing1 shows my pages as I want for testing purposes, my problem is this. On my testing2.html page that displays, I have a list "uuup", my problem is, I only want to show uuup.0 on page 1, uuup.1 on page 2, uuup.2 on page 3, etc. I can't seem to figure out how to use the pk as an index? I set a diff variable in my views page and set it to int(item) and printed it out on each page to confirm that each subpage showed it as 1/2/3/4/etc so I am unsure how to call it to use an index to my "uuup" list?

CodePudding user response:

You can slice in your view like this:

def current_games(request, pk):
     item = Nbav8.objects.using('totals').get(pk=pk)
     index = pk - 1
     items2 = CurrentDayStats.objects.using('totals').values_list('home_team_over_under_field', flat=True)[index]
return render(request, 'home/testing2.html', {'item': item, 'uuup':items2})
  •  Tags:  
  • Related