开发者

Why is my HTML template in Django not rendering in browser?

I am having issues with rendering an HTML template that has variables passed to it from my views.py in the Django project.

Everything seems to be working with the exception that when you visit the HTML in a browser on my local machine it renders the HTML code, instead of the designed page with content.

the files are below.

VIEWS.PY

from django.shortcuts import render
import datetime
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore


db = firestore.Client()

config = {
    "apiKey": "XXXXXXXXXXXXXXXXXXX",
    "authDomain": "XXXXXXXXXXXXXXXXXXX.firebaseapp.com",
    "databaseURL": "https://XXXXXXXXXXXXXXXXXXX.firebaseio.com",
    "projectId": "XXXXXXXXXXXXXXXXXXX",
    "storageBucket": "XXXXXXXXXXXXXXXXXXX.appspot.com",
    "messagingSenderId": "XXXXXXXXXXXXXXXXXXX",
    "appId": "XXXXXXXXXXXXXXXXXXX",
    "measurementId": "XXXXXXXXXXXXXXXXXXX",
    "serviceAccount": "XXXXXXXXXXXXXXXXXXX.json",
    }

# DATABASE
# Use the application default credentials.
cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred)
firestore_client = firestore.client()


# TIME & DATE
today_date = datetime.datetime.now()
tomorrow_date = today_date + datetime.timedelta(days=1)
games_today = today_date.date()
games_tomorrow = tomorrow_date.date()
games_today_formatted = games_today.strftime("%Y-%m-%d")
games_tomorrow_formatted = games_tomorrow.strftime("%Y-%m-%d")





def basketball_nba(request):

    ############################################################################
    # ENTAIN (NEDS/LADBROKES)
    ############################################################################
    # Query firestore database for NBA games
    nba_events = db.collection('entain_au').document('basketball_nba').collection('event_odds').stream()
    event_info = [doc.to_dict() for doc in nba_events]

    # print(event_info)

    # Filter NBA games by dates
    events_today = [event for event in event_info if event['event_odds']['Event']['StartTime'][:10] == games_today]
    events_tomorrow = [event for event in event_info if
                       event['event_odds']['Event']['StartTime'][:10] == games_tomorrow]

    # print(events_today)
    # print('Tomorrow:', events_tomorrow)

    # List of NBA games today win odds data
    entain_h2h_today = []
    # List of NBA games tomorrow win odds data
    entain_h2h_tomorrow = []

    # Iterate through NBA games json for today's games to get win odds data
    try:
        for h2h in events_today:
            if h2h['event_odds']['Event']['Markets']:
                for market in h2h['event_odds']['Event']['Markets']:
                    if market['Name'] == 'Head To Head':
                        print(market['Selections'])
                        if market['Selections']:
                            game_data = {}  # Create empty dictionary to store game data
                            for selection in market['Selections']:
                                if selection['Role'] == 'Home':
                                    game_data['home_team'] = selection['Name']
                     开发者_如何学C               game_data['home_odds'] = selection['WinPrice']
                                if selection['Role'] == 'Away':
                                    game_data['away_team'] = selection['Name']
                                    game_data['away_odds'] = selection['WinPrice']
                            entain_h2h_today.append(game_data)  # Append game data to list
    except KeyError:
        print('No NBA games today')

    # Iterate through NBA games json for today's games to get win odds data
    try:
        for h2h in events_tomorrow:
            if h2h['event_odds']['Event']['Markets']:
                for market in h2h['event_odds']['Event']['Markets']:
                    if market['Name'] == 'Line':
                        print(market['Selections'])
                        if market['Selections']:
                            game_data = {}  # Create empty dictionary to store game data
                            for selection in market['Selections']:
                                if selection['Role'] == 'Home':
                                    game_data['home_team'] = selection['Name']
                                    game_data['home_handicap'] = selection['Handicap']
                                    game_data['home_odds'] = selection['WinPrice']
                                if selection['Role'] == 'Away':
                                    game_data['away_team'] = selection['Name']
                                    game_data['away_odds'] = selection['WinPrice']
                            entain_h2h_tomorrow.append(game_data)  # Append game data to list
    except KeyError:
            print('No NBA games tomorrow')

    ############################################################################
    # UNIBET
    ############################################################################

    # Query firestore database for NBA games
    nba_events = firestore_client.collection('unibet_au') \
        .document('basketball_nba') \
        .collection('event_odds') \
        .stream()

    # Convert the nba_events generator object to a list
    nba_events_list = list(nba_events)

    # Print the number of events in the nba_events_list variable
    print(len(nba_events_list))

    # Parse event data
    event_info = [doc.to_dict() for doc in nba_events_list]
    # print(event_info)

    # Filter NBA games by dates
    events_today = [event for event in event_info if
                    event['event_odds']['events'][0]['start'][:10] == games_today_formatted]
    events_tomorrow = [event for event in event_info if
                       event['event_odds']['events'][0]['start'][:10] == games_tomorrow_formatted]

    # Print the number of events today and tomorrow
    print(len(events_today))
    # print(len(events_tomorrow))

    # Print the events today and tomorrow
    # print(events_today)
    # print(events_tomorrow)

    # List of NBA games today win odds data
    unibet_h2h_today = []
    # List of NBA games tomorrow win odds data
    unibet_h2h_tomorrow = []

    # Set the market type you are looking for
    market_type = "Head To Head - Including Overtime"

    # Use a list comprehension to extract the data for each event
    h2h_data = [{"game": event['event_odds']['events'][0]['name'],
                 "market_type": bet_offer['criterion']['label'],
                 "home_team": bet_offer['outcomes'][0]['englishLabel'],
                 "home_team_h2h_odds": bet_offer['outcomes'][0]['odds'],
                 "away_team": bet_offer['outcomes'][1]['englishLabel'],
                 "away_team_h2h_odds": bet_offer['outcomes'][1]['odds'],
                 }
                for event in event_info
                for bet_offer in event['event_odds']['betOffers']
                if bet_offer['criterion']['label'] == market_type]

    # Filter & print the h2h_data list
    for win_odds in h2h_data:
        game = win_odds['game']
        home_team = win_odds['home_team']
        home_team_h2h_odds = win_odds['home_team_h2h_odds'] / 1000
        away_team = win_odds['away_team']
        away_team_h2h_odds = win_odds['away_team_h2h_odds'] / 1000
        unibet_h2h_today.append({
            "game": game,
            "home_team": home_team,
            "home_team_h2h_odds": home_team_h2h_odds,
            "away_team": away_team,
            "away_team_h2h_odds": away_team_h2h_odds,
        })
        print(unibet_h2h_today)
        unibet_h2h_tomorrow.append({
            "game": game,
            "home_team": home_team,
            "home_team_h2h_odds": home_team_h2h_odds,
            "away_team": away_team,
            "away_team_h2h_odds": away_team_h2h_odds,
        })

        # Create an HttpResponse object by rendering an HTML template
        response = render(request, "nba.html", {
            'entain_h2h_today': entain_h2h_today,
            'entain_h2h_tomorrow': entain_h2h_tomorrow,
            'unibet_h2h_today': unibet_h2h_today,
            'unibet_h2h_tomorrow': unibet_h2h_tomorrow,
        })
        # Return the response
        return response

URLS.PY

from django.contrib import admin
from django.urls import path
import nba.views as views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('nba/', views.basketball_nba, name='basketball_nba'),
]

NBA.HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>NBA TESTING</title>
</head>
<body>
<!-- TODAY'S EVENTS - WIN ODDS -->
<h3>Today's NBA Games Odds</h3>

<div class="table-responsive" style="width: 1000px;">
    <table class="table">
        <thead>
            <tr>
                <th>Bookie</th>
                <th>Home</th>
                <th>Home Odds</th>
                <th>Away</th>
                <th>Away odds</th>
            </tr>
        </thead>
        <tbody>
            {% for h2h in entain_h2h_today %}
                <tr>
                    <td>Entain</td>
                    <td>{{ h2h.home_team }}</td>
                    <td>{{ h2h.home_odds }}</td>
                    <td>{{ h2h.away_team }}</td>
                    <td>{{ h2h.away_odds }}</td>
                </tr>
            {% endfor %}
            {% for h2h in unibet_h2h_today %}
                <tr>
                    <td>unibet</td>
                    <td>{{ h2h.home_team }}</td>
                    <td>{{ h2h.home_team_h2h_odds }}</td>
                    <td>{{ h2h.away_team }}</td>
                    <td>{{ h2h.away_team_h2h_odds }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
</div>


</body>
</html>

Page in browser look:

Why is my HTML template in Django not rendering in browser?


It seems to be like you are not returning h2h anywhere in views.

Have a glance at this structure:

def user_coach_response_view(request):


   data=UserFitnessModel.objects.all()

   return render(request,'user/user-coach-response.html',{"data":data})

            {% for k  in  data  %}
        <div class="d-block services-wrap text-center">
          <div class="img"><img style="width:320px; height:190px;" src="{% static 'main/images//bg_2.jpg'  %}"></div>
          <div class="media-body p-2 mt-3">
            <h3 class="heading">Name: {{k.user_id.name}}</h3>
            <h3 class="heading">Hieght: {{k.hieght}}cm</h3>
            <h3 class="heading">Wieght: {{k.wieght}}kg</h3>
            <p><a href="/user-coach-response/{{k.user_fitness_id}}" class="btn btn-primary btn-outline-primary">Read more</a></p>
          </div>
        </div>  
        {% endfor %}    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜