简体   繁体   中英

UnboundLocalError local variable 'context' referenced before assignment Django

I get the error below immediately after i add a new root url inside the root urls.py.

When i remove the dashboard view, url and i try to load index view, it renders successfully. What am i doing wrong or what can i do to resolve the issue.

Error message

UnboundLocalError at /blogapp/
local variable 'context' referenced before assignment
Request Method: GET
Request URL:    http://127.0.0.1:8000/blogapp/
Django Version: 4.0.2
Exception Type: UnboundLocalError
Exception Value:    
local variable 'context' referenced before assignment

My views

from multiprocessing import context
import re
from django.shortcuts import render
from django.http import HttpResponse
from .odd_finder_func import *


def index(request):
    if request.method == 'POST':
        odd1 = float(request.POST.get('odd1'))
        odd2 = float(request.POST.get('odd2'))
        odd3 = float(request.POST.get('odd3'))

        func_def = odd_finder_true(odd1, odd2, odd3)

        context = {
            'Juice': func_def['Juice'],
            'TotalImpliedProbability': func_def['TotalImpliedProbability'],
            'HomeOdd': func_def['HomeOdd'],
            'DrawOdd': func_def['DrawOdd'],
            'AwayOdd': func_def['AwayOdd'],
            'Home_True_Odd': func_def['Home_True_Odd'],
            'Draw_True_Odd': func_def['Draw_True_Odd'],
            'Away_True_Odd': func_def['Away_True_Odd'],
            'True_Probability': func_def['True_Probability']
            }

        context = context

    return render(request, 'index.html', context)

def dashboard(request):
    return render(request, 'dashboard.html')

blogapp urls.py

from django.urls import path
from .views import *
from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

myblog urls.py the root file.

from django.contrib import admin
from django.urls import path, include
from blogapp import views

urlpatterns = [ 
    path('admin/', admin.site.urls),
    path('', views.dashboard, name='dashboard'),
    path('blogapp/', include('blogapp.urls')),
]

index.html

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>

    <div class="container">
        <!-- Content here -->

        
    <form action="" method="post">
        {% csrf_token %}
        <div class="mb-3">
            <label for="Odd1" class="form-label">Home Odd</label>
            <input type="number" class="form-control" name="odd1" id="odd1" min="0" value=" " step=".01" required='required'>
          </div>
        <div class="mb-3">
          <label for="Odd2" class="form-label">Draw Odd</label>
          <input type="number" class="form-control" name="odd2" id="odd2" min="0" value=" " step=".01" required='required'>
        </div>

        <div class="mb-3">
            <label for="Odd3" class="form-label">Away Odd</label>
            <input type="number" class="form-control" name="odd3" id="odd3" min="0" value=" " step=".01" required='required'>
          </div>
       
        <button type="submit" class="btn btn-primary">Submit</button>
        <input class="btn btn-primary" type="reset" value="Reset">
      </form>

      </div>
       

      <div class="container">
        <p>Total Implied probability percentage: {{TotalImpliedProbability}}</p>
        <p>Bookie juice is: {{Juice}}</p>
        <p>Home Odd: {{HomeOdd}}</p>
        <p>Draw Odd: {{DrawOdd}}</p>
        <p>Away Odd: {{AwayOdd}}</p>
        <p>Home True Odd: {{Home_True_Odd}}</p>
        <p>Draw True Odd: {{Draw_True_Odd}}</p>
        <p>Away True Odd: {{Away_True_Odd}}</p>
        <p>True Probability is: {{True_Probability}}</p>
       
      </div>

      



    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>


    
    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
    -->
  </body>
</html>

Below is an attachment of the django app files is set up.

在此处输入图像描述

You need to define context when if request.method == "GET"

def index(request):
    if request.method == "POST":
        odd1 = float(request.POST.get("odd1"))
        odd2 = float(request.POST.get("odd2"))
        odd3 = float(request.POST.get("odd3"))

        func_def = odd_finder_true(odd1, odd2, odd3)

        context = {
            "Juice": func_def["Juice"],
            "TotalImpliedProbability": func_def["TotalImpliedProbability"],
            "HomeOdd": func_def["HomeOdd"],
            "DrawOdd": func_def["DrawOdd"],
            "AwayOdd": func_def["AwayOdd"],
            "Home_True_Odd": func_def["Home_True_Odd"],
            "Draw_True_Odd": func_def["Draw_True_Odd"],
            "Away_True_Odd": func_def["Away_True_Odd"],
            "True_Probability": func_def["True_Probability"],
        }

        context = context

        # INDENT THIS
        return render(request, "index.html", context)
    else:
        # WHAT IS THE CONTEXT WHEN request.method == "GET" ?
        return render(request, "index.html", {})

The problem is that the variable context you created has the same name as the context you imported from multiprocessing at the top of the file. Changing the variable name should fix the problem.

from multiprocessing import context
import re
from django.shortcuts import render
from django.http import HttpResponse
from .odd_finder_func import *


def index(request):
    if request.method == 'POST':
        odd1 = float(request.POST.get('odd1'))
        odd2 = float(request.POST.get('odd2'))
        odd3 = float(request.POST.get('odd3'))

        func_def = odd_finder_true(odd1, odd2, odd3)

        response_context = {
            'Juice': func_def['Juice'],
            'TotalImpliedProbability': func_def['TotalImpliedProbability'],
            'HomeOdd': func_def['HomeOdd'],
            'DrawOdd': func_def['DrawOdd'],
            'AwayOdd': func_def['AwayOdd'],
            'Home_True_Odd': func_def['Home_True_Odd'],
            'Draw_True_Odd': func_def['Draw_True_Odd'],
            'Away_True_Odd': func_def['Away_True_Odd'],
            'True_Probability': func_def['True_Probability']
            }

    return render(request, 'index.html', response_context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM