This is my error message:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/mainpage.html
Django Version: 3.2.12
Python Version: 3.7.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'website']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.security.SecurityMiddleware',
'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',
'whitenoise.middleware.WhiteNoiseMiddleware')
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\user\desktop\dentist\website\views.py", line 40, in mainpage
c.execute(query)
Exception Type: UnboundLocalError at /mainpage.html
Exception Value: local variable 'query' referenced before assignment
This is my python views.py
def logout(request):
try:
del request.session['your-email']
except KeyError:
pass
result_dict = {}
result_dict['logout_success'] = 'See you next time! You have sucessfuly logged out'
return render(request, 'home.html', result_dict)
def mainpage(request):
if 'your-email' not in request.session:
if request.method == "POST":
email = request.POST['your-email']
password = request.POST['your-password']
if email!='' and password!='':
verification = "SELECT * FROM users WHERE email = '" email "' AND password = '" password "';"
c = connection.cursor()
c.execute(verification)
account_exist = c.fetchall()
results_dict = {}
if not account_exist:
results_dict = {'error':'Please try again. Entered username or password is wrong'}
return render(request, 'login.html',results_dict)
request.session['your-email'] = email
else:
query = "SELECT email, display_name, age, phone_number, vaccination_status, rating, count_rate FROM users WHERE email = '" request.session['your-email'] "';"
c = connection.cursor()
c.execute(query) # this is line 40 the error message
results = c.fetchall()
result_dict = {'records': results}
return render(request, 'mainpage.html', result_dict)
def login(request):
if request.method == "POST":
display_photo = request.POST['your-photo']
display_name = request.POST['your-name']
email = request.POST['your-email']
age = request.POST['your-age']
phone_number = request.POST['phone-number']
gender = request.POST['your-gender']
vaccination_status = request.POST['your-vaccination']
password = request.POST['your-password']
if display_photo!= '' and display_name != '' and email != '' and age !='' and phone_number !='' and gender !='' and vaccination_status !='' and password !='':
email_check = "SELECT * FROM users WHERE email = '" email "';"
c = connection.cursor()
c.execute(email_check)
emails_exist = c.fetchall() #container
results_dict = {}
if len(display_name)>128:
results_dict['name_warning'] = 'Your name cannot be more than 128 characters'
if len(email) > 128:
results_dict['email_verifier'] = ' Your email cannot be more than 128 characters'
elif emails_exist:
results_dict['email_verifier']='There is already an account with email ' email
if len(password) < 6:
results_dict['pw_warning'] = 'Your password cannot be less than 6 characters'
elif len(password) >64:
results_dict['pw_warning'] = 'Your password cannot be more than 64 characters'
if results_dict:
return render(request,'booknow.html',results_dict)
insert_query = "INSERT INTO users (display_photo, display_name, email, age, phone_number, gender, vaccination_status, password, rating, count_rate) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s');" % (display_photo, display_name,email,age,phone_number,gender,vaccination_status,password,0,0)
c = connection.cursor()
c.execute(insert_query)
return render(request, 'login.html')
This is the HTML code (mainpage.html):
<html>
<head>
<title> RentBuddy! </title>
</head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #000000;
text-align: left;
padding: 2px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
<body style="margin:50;padding:50">
<div id="clockbox" style="font:12pt TimesNewRoman; color:#FF4500; text-align:right"></div>
<script type="text/javascript">
var tday=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var tmonth=["January","February","March","April","May","June","July","August","September","October","November","December"];
function GetClock(){
var d=new Date();
var nday=d.getDay(),nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getFullYear();
var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds(),ap;
if(nhour==0){ap=" AM";nhour=12;}
else if(nhour<12){ap=" AM";}
else if(nhour==12){ap=" PM";}
else if(nhour>12){ap=" PM";nhour-=12;}
if(nmin<=9) nmin="0" nmin;
if(nsec<=9) nsec="0" nsec;
var clocktext="" tday[nday] ", " tmonth[nmonth] " " ndate ", " nyear " " nhour ":" nmin ":" nsec ap "";
document.getElementById('clockbox').innerHTML=clocktext;
}
GetClock();
setInterval(GetClock,1000);
</script>
<br>
<form method = "POST" action = "home.html"> {%csrf_token%} <button type="submit">Logout</button> </form>
<a href = 'settings.html'> Click here to become a buddy! </a>
</br>
<h2 style = "color:rgba(400,133,0); font:20pt;text-align:center"> RentBuddy :)</h2>
{{logout_success}}
<body>
{% for rows in records %}
<p> Welcome back, {{rows.1}} </p>
<p>Here's your account information as of now:</p>
<table border = "1">
<tr>
<td> Email Address </td>
<td> Name </td>
<td> Age </td>
<td> Phone Number </td>
<td> Vaccination Status </td>
<td> Rating </td>
<td> Number of times you have been rated </td> </tr>
<tr>
<td> {{rows.0}} </td>
<td> {{rows.1}} </td>
<td> {{rows.2}} </td>
<td> {{rows.3}} </td>
<td> {{rows.4}} </td>
<td> {{rows.5}} </td>
<td> {{rows.6}} </td>
{% endfor %}
</tr> <br> </table> <br>
<p> Check out our buddies :) </p>
<p> Search by the buddy's name: [sorted by alphabetical order ascendingly]</p>
<form method = "GET" action = "result.html"> <!-- This means after we click submit, will go to another page called result wiht the get mehtod -->
<input type = "text" name = "age"/>
<input type = "submit" value = "Search Buddy by Age">
</form>
<p> Search by the buddy's hourly rate: [sorted based on cheapest price]</p>
<form method = "GET" action = "result.html"> <!-- This means after we click submit, will go to another page called result wiht the get mehtod -->
<input type = "text" name = "hourly-rate"/>
<input type = "submit" value = "Search Buddy by Hourly Rate">
</form>
<p> Search by buddy's preference: [sorted by genre alphabetically ascendingly] </p>
<form method = "GET" action = "result.html"> <!-- This means after we click submit, will go to another page called result wiht the get mehtod -->
<input type = "text" name = "interests"/>
<input type = "submit" value = "Search Buddy by Interests">
</form>
<p> Note, if you want to search multiple interests (not recommended), you need to : </p>
<ul>
<li>sort them alphabetically, for example 'Running|Cooking'</li>
<li> You would need to separate it by a | sign (no space) </li> </ul>
<br>
<p> Want to express your gratitude or misery in your experience? Do rate your buddy! Hope your 1st date went well :D [1 to 5] </p>
<form method="POST" action="rate.html"> {% csrf_token %}
<input type="text" placeholder= "Who do you want to rate? (email)" name="email" required><br>
<input type="number" placeholder= "What's the rating? (1-5)" name="rating"
min = '1' max = '5'
oninvalid="this.setCustomValidity('Your rating can only be from 1 to 5')" oninput="this.setCustomValidity('')"required><br>
<input type="submit" value="Rate this person!"> </form>
<font color = 'red'> {{email}} <br>
{{err}}
</body>
</html>
Im currently trying to make the log in page identify the user that logs in, after which it will display their information in a form of a table using the query that i will be executing in SQL. Im not sure why there is the error.
CodePudding user response:
I tried to add comments to your code, essentially your error means you are not defining query
in all the possible code paths. Your code is confusing, I would just force the user to login before accessing your mainpage instead of trying to have the mainpage login your user.
Your also storing plain-text passwords which is a very bad practice.
def mainpage(request):
if 'your-email' not in request.session:
if request.method == "POST":
email = request.POST['your-email']
password = request.POST['your-password']
if email!='' and password!='':
verification = "SELECT * FROM users WHERE email = '" email "' AND password = '" password "';"
c = connection.cursor()
c.execute(verification)
account_exist = c.fetchall()
results_dict = {}
if not account_exist:
results_dict = {'error':'Please try again. Entered username or password is wrong'}
return render(request, 'login.html',results_dict)
request.session['your-email'] = email
# You would need to set your query here so it can be used below
query = "SELECT email, display_name, age, phone_number, vaccination_status, rating, count_rate FROM users WHERE email = '" request.session['your-email'] "';"
else:
# If email=='' and password=='' you need to render your login template
return render(request, 'login.html')
else:
# If request.method == "GET" you need to render your login template
return render(request, 'login.html')
else:
query = "SELECT email, display_name, age, phone_number, vaccination_status, rating, count_rate FROM users WHERE email = '" request.session['your-email'] "';"
c = connection.cursor()
c.execute(query) # this is line 40 the error message
results = c.fetchall()
result_dict = {'records': results}
return render(request, 'mainpage.html', result_dict)