UnboundLocalError local variable 'context' referenced before assignment Django - python

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)

Related

Login and Authentication in Django

I am trying to create a login function and login authentication in the views.py inside def login(request) for particular username and password from my model class "Signup" . Could someone please help me in my existing code how to do so or share any resources to perform the following operation.
P.S. I am new to Django and getting overwhelmed by the information present in the internet due which couldn't get the solution to my problem.
I am adding my code snippets for models.py , views.py , urls.py and login.html .
"models.py"
from django.db import models
# Create your models here.
class SignUp(models.Model):
username= models.CharField(max_length=100)
email=models.EmailField(max_length=254)
password=models.CharField(max_length=20)
address=models.CharField(max_length=250)
"views.py"
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import SignUp
from django.contrib.auth import login,authenticate,logout
# Create your views here.
def login(request):
if request.method == 'POST':
username= request.POST['username']
password= request.POST['password']
user = authenticate(username=username,password=password)
html2 = "<html><body>No such user</body></html>"
if user is not None:
login(request,user)
return redirect('')
else:
return HttpResponse(html2)
else:
return render(request,'login.html')
def signup(request):
if request.method == 'POST':
username= request.POST['username']
email= request.POST['email']
password1= request.POST['password1']
password2= request.POST['password2']
address= request.POST['address']
html = "<html><body>Confirm Password and Password should be same </body></html>"
html1= "<html><body>User Already present </body></html>"
if password1 != password2:
return HttpResponse(html)
else:
for instance in SignUp.objects.all():
if (instance.username == username) or (instance.email==email):
return HttpResponse(html1)
signup=SignUp(username=username,email=email,password=password1,address=address)
signup.save()
return redirect('login')
else:
return render(request,'signup.html')
"urls.py"
from django.urls import path
from . import views
urlpatterns = [
path('',views.signup, name='signup'),
path('signup/',views.signup,name='signup'),
path('login/',views.login,name='login'),
]
"login.html"
<!--
Author: Colorlib
Author URL: https://colorlib.com
License: Creative Commons Attribution 3.0 Unported
License URL: http://creativecommons.org/licenses/by/3.0/
-->
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!-- Custom Theme files -->
<link href="{% static 'styles/styles.css' %}" rel="stylesheet" type="text/css" media="all" />
<!-- //Custom Theme files -->
<!-- web font -->
<link href="//fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,700,700i" rel="stylesheet">
<!-- //web font -->
</head>
<body>
<!-- main -->
<div class="main-w3layouts wrapper">
<h1>LOGIN</h1>
<div class="main-agileinfo">
<div class="agileits-top">
<form action="/login/" method="post">
{% csrf_token %}
<input class="text" type="text" name="username" placeholder="Username" required="">
<input class="text" type="password" name="password" placeholder="Password" required="">
<input type="submit" value="LOGIN">
</form>
<!-- <p>Don't have an Account? Login Now!</p> -->
</div>
</div>
<!-- copyright -->
<!-- <div class="colorlibcopy-agile">
<p>© 2018 Colorlib Signup Form. All rights reserved | Design by Colorlib</p>
</div> -->
<!-- //copyright -->
<ul class="colorlib-bubbles">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<!-- //main -->
</body>
</html>
okay i agree with yuv,
What you want to do is basically replace this
class SignUp(models.Model):
username= models.CharField(max_length=100)
email=models.EmailField(max_length=254)
password=models.CharField(max_length=20)
address=models.CharField(max_length=250)
with:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
"""
add the required fields that you need apart from django's builtin
user model
"""
address = models.Textfield(_("address"))
Now this can help fulfil the requirement of model and you will be able use the authenticate method on fields such as username and email with password that you store during signup using set_password function to hash the password and store it in your db which can be used securely afterwords.

Can't save data from HTML form to database Django

I'm trying to save data entered in this form (below) into a database:
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TODO</title>
</head>
<body>
{% if user.is_authenticated %}
<form id='add-task' method='post'>{% csrf_token %}
<div class="mb-3">
<input type="text" class="form-control" name="task-name" placeholder="task name">
</div>
<div class="mb-3">
<input type="text" class="form-control" name="task-desc" placeholder="description">
</div>
<div class="mb-3">
<input type="text" class="form-control" name="deadline" placeholder="YYYY-MM-DD">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</br></br>
{% endif %}
</body>
</html>
I'm not sure if I poorly formatted the code or if I'm using the wrong HTML. Is it possible to do this using HTML or should I just use a ModelForm?
views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import logout
from django.contrib.auth.models import Group
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from .models import Task
def home(request):
# checks if user is logged in so that it can display task creation page
if request.user.is_authenticated:
return render(request, 'home.html', {'user': request.user})
# add new task ---> ALL THE CODE BELOW
if request.method == 'POST':
name = str(request.POST['task-name'])
desc = str(request.POST['task-desc'])
deadline = request.POST['deadline']
task = Task(task_name=name, task_desc=desc, task_deadline=deadline)
task.save()
#messages.success(request, "You've added a task.")
return render(request, 'home.html', {})
If you want to get your code as it is running:
def home(request):
# checks if user is logged in so that it can display task creation page
if request.user.is_authenticated:
if request.method == 'POST':
name = str(request.POST['task-name'])
desc = str(request.POST['task-desc'])
deadline = request.POST['deadline']
task = Task(task_name=name, task_desc=desc, task_deadline=deadline)
task.save()
return render(request, 'home.html', {'user': request.user})
else:
return render(request, 'home.html', {})
But you don't need to pass in user as context. This is available anyway.
So you could just do:
def home(request):
if request.method == 'POST':
name = str(request.POST['task-name'])
desc = str(request.POST['task-desc'])
deadline = request.POST['deadline']
task = Task(task_name=name, task_desc=desc, task_deadline=deadline)
task.save()
return render(request, 'home.html')
And request.user will still be available as {{ request.user.is_authenticated }} in your template.

no redirect from auth_view.LoginView.as_view(authentication_form=LoginForm)

i am using auth_view.LoginView.as_view() urls.py as default login in django. To add more fields i used custom form with AuthenticationForm in form.py, but after using custom form i cannot redirect from login page as i click submit button
here is my form.py
'''
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm
class LoginForm(AuthenticationForm):
user_type_choice = (('visitor', 'Visitor'),('guest', 'Guest'),('contractor',
'Contractor'))
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
user_type = forms.MultipleChoiceField(choices=user_type_choice,
widget=forms.NullBooleanSelect, required=True)
here is my urls.py
from django.urls import path
from django.contrib.auth import views as auth_view
from account.form import LoginForm
from . import views
urlpatterns =[
path('login/', auth_view.LoginView.as_view(authentication_form=LoginForm),
name='login'),
path('logout/', auth_view.LogoutView.as_view(), name='logout'),
path('', views.dashboard, name='dashboard')
]
here is my views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# Create your views here.
#login_required
def dashboard(request):
render(request, 'account/dashboard', {'section': dashboard})
sorry for bad english. i am a newbie, please pardon me for my mistakes
here is login.html
{%load static%}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type='text/css' href="{%static 'css/loginstyle.css'%}">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#800&display=swap" rel="stylesheet">
<title></title>
</head>
<body>
<div class='header'>
<img src="{%static 'img/healthlogo.png'%}" height="80" weidth="80">
<h1>AGED CARE PORTAL
</h1>
</div>
<form method="POST" class="form">
{%csrf_token%}
<br>
<br>
<input align='center' class="credentials" placeholder="ID"{{form.username}}
</div>
<br>
<div>
<input class="credentials" placeholder="Password" {{form.password}}
</div>
<div align='center' >
<select class='selector'{{form.user_type}}</select>
</div>
<p align='center'><input class='logtton' type='submit' value='Log-In'></p>
<input type="hidden" name="next" value="{{next}}">
</form>
</body>
</html>

How can I make Django render in the browser?

I'm trying to utilize Django forms.ModelForm function. However, I can not get it to render in the browser (Firefox and Chrome tested). In both browser inspection of code, the table\form does not show and there is no error coming from Django at all. The only thing that shows from the html file is the "Save button" Is there something I am missing here?
In Models.py
from django.db import models
class Product_sell_create(models.Model):
product_product_sell = models.CharField(max_length=120)
product_price_sell = models.DecimalField(decimal_places=2, max_digits=500)
product_volume_sell = models.DecimalField(decimal_places=2, max_digits=500)
product_location_sell = models.CharField(max_length=120)
product_description_sell = models.TextField(blank=False, null=False)
Forms.py
from django import forms
from .models import Product_sell_create
class ProductName(forms.ModelForm):
class Meta:
model = Product_sell_create
fields = [
'product_product_sell',
'product_volume_sell',
'product_price_sell',
'product_location_sell',
'product_description_sell'
]
Views.py
from django.shortcuts import render
from .forms import ProductName
def products_create_view(request):
form = ProductName(request.POST or None)
if form.is_valid():
form.save()
form = ProductName()
context = {
'form': form
}
return render(request, "sell.html", context)
sell.html
{% include 'navbar.html' %}
<h1> Upper test</h1>
<form>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
<h1> TEST </h1>
{% block content %}
{% endblock %}
just did it, you would have problems POSTing your object too:
views.py:
from django.shortcuts import render, redirect
from .forms import ProductName
from .models import Product_sell_create
def products_create_view(request):
if request.method == 'POST':
form = ProductName(request.POST)
if form.is_valid():
prod = form.save(commit=False)
prod.save()
return redirect('../thanks')
else:
form = ProductName()
context = {
'form': form
}
return render(request, "form_test.html", context)
def thanks_view(request):
query = Product_sell_create.objects.all()
return render (request, 'thanks.html', {'query' : query})
forms.py and models.py keeps the same
sell.html:
<h1> Upper test</h1>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
<h1> TEST2 </h1>
thanks.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>{{ query }}</h1>
<h2>THANKS</h2>
</body>
</html>
did you create the 'sell.html' inside a 'templates' folder in your app folder?
MyApp/templates/sell.html

How would I be able to store these first names and last names in database automatically?

I’m currently teaching myself Django and I want to know how to store first names and last names in a database in its appropriate column. I’m familiar with the SQL commands. I know how to manually store them in the database with the SQL commands using the code in the models.py file but this time, I want these first names and last names stored in the database upon the user hitting Submit after filling out the text fields so that next time when I manually look up what’s inside my database, I’ll see what the user has submitted.
How would I go about starting this?
Here's my urls.py file:
from django.conf.urls import url
from . import views
urlpatterns = [
# /music/
url(r'^$', views.index, name='index'),
# /music/71
url(r'^(?P<user_id>[0-9]+)/$', views.detail),
]
Here's my views.py file:
from django.http import HttpResponse
from django.template import loader
def index(request):
template = loader.get_template('music/index.html')
return HttpResponse(template.render())
def detail(request, user_id): # Testing out page 2
return HttpResponse("<h2>Page # (testing this out) " + str(user_id) + "</h2>")
Here's my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form action="#">
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="email" class="form-control" id="firstName" placeholder="Enter first name" name="firstName">
</div>
<div class="form-group">
<label for="">Last Name:</label>
<input type="email" class="form-control" id="lastName" placeholder="Enter last name" name="lastName">
</div>
</form>
<div class="checkbox">
<label><input type="checkbox" name="remember">Remember me</label></div></br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</body>
</html>
Here's my models.py file:
from django.db import models
class User(models.Model):
firstName = models.CharField(max_length=200)
lastName = models.CharField(max_length=200)
def __str__(self):
return self.firstName + ' - ' + self.lastName
class UI(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
You could write the view somewhat like this,
def index(request):
if request.method == 'POST':
first_name = request.POST.get('firstName')
last_name = request.POST.get('lastName')
if first_name and last_name:
user = User.objects.create(first_name=first_name, last_name=last_name)
else:
return Httpresponse('Not Done!')
return render(request, 'music/index.html')

Categories