HTML printing is wrong - python

So I've been looking at this for over an hour and I cannot figure out what the heck is going on.
The script is printing only a ">"
It's suppose to print the full HTML and then, after the form is submitted, print "print_after"
import webapp2
class MainHandler(webapp2.RequestHandler):
def get(self):
p = Page()
if self.request.GET:
name = self.request.GET['name']
age = self.request.GET['age']
time = self.request.GET['time']
model = self.request.GET['model']
radio = self.request.GET['trade']
self.response.write(p.print_after(name, age, time, model, radio))
print name + age + time + model + radio
else:
self.response.write(p.print_one)
class Page(object):
def __init__(self):
self.page_body = '''
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/main.css">
<title>Audi Test Drive Request</title>
</head>
<body>
<img src="assets/custom/images/logo.png" title="logo" alt="" width="200px" height="150px"/>
<h3>It's awesome that you want to test-drive one of our vehicles</h3>
<form method="GET" action="">
<label>Name</label>
<br>
<input type="text" name="name" required>
<br>
<label>Age</label>
<br>
<input type="text" name="age" required>
<br>
<label>Time</label>
<br>
<select name="time" required>
<option value="12:00 PM">12:00 PM</option>
<option value="12:30 PM">12:30 PM</option>
<option value="1:00 PM">1:00 PM</option>
</select>
<br>
<label>Model</label>
<br>
<select name="model" required>
<option value="2008 Audi A4">2008 Audi A4</option>
<option value="2008 Audi S4">2008 Audi S4</option>
<option value="2008 Audi RS4">2008 Audi RS4</option>
</select>
<br>
<label>Are you trading in a vehicle?</label>
<br>
<input type="radio" name="trade" value="yes" required>Yes<br>
<input type="radio" name="trade" value="no" required>No<br>
<br>
<input type="submit" value="Request Test Drive">
</form>
</body>
</html>
'''
self.page_after = '''
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/main.css">
<title>Audi Test Drive Request</title>
</head>
<body>
<img src="assets/custom/images/logo.png" title="logo" alt="" width="200px" height="150px"/>
<h3>It's awesome that you want to test-drive one of our vehicles</h3>
</body
</html>
'''
def print_one(self):
page_content = self.page_body
page_content = page_content.format(**locals())
return page_content
def print_after(self, name, age, time, model, radio):
after_page_content = self.page_after
after_page_content = after_page_content.format(**locals())
return after_page_content
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)

I tested your code and rearranged it a little. I used http post for submitting the form and then it prints the form variables.
import webapp2
class HelloWebapp2(webapp2.RequestHandler):
def get(self):
self.response.write('''<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/main.css">
<title>Audi Test Drive Request</title>
</head>
<body>
<img src="assets/custom/images/logo.png" title="logo" alt="" width="200px" height="150px"/>
<h3>It's awesome that you want to test-drive one of our vehicles</h3>
<form method="POST" action="">
<label>Name</label>
<br>
<input type="text" name="name" required>
<br>
<label>Age</label>
<br>
<input type="text" name="age" required>
<br>
<label>Time</label>
<br>
<select name="time" required>
<option value="12:00 PM">12:00 PM</option>
<option value="12:30 PM">12:30 PM</option>
<option value="1:00 PM">1:00 PM</option>
</select>
<br>
<label>Model</label>
<br>
<select name="model" required>
<option value="2008 Audi A4">2008 Audi A4</option>
<option value="2008 Audi S4">2008 Audi S4</option>
<option value="2008 Audi RS4">2008 Audi RS4</option>
</select>
<br>
<label>Are you trading in a vehicle?</label>
<br>
<input type="radio" name="trade" value="yes" required>Yes<br>
<input type="radio" name="trade" value="no" required>No<br>
<br>
<input type="submit" value="Request Test Drive">
</form>
</body>
</html>
''')
def post(self):
if self.request.POST:
name = self.request.POST['name']
age = self.request.POST['age']
time = self.request.POST['time']
model = self.request.POST['model']
radio = self.request.POST['trade']
self.response.write(name +" " + age +" " + time +" " + model +" " + radio)
app = webapp2.WSGIApplication([
('/', HelloWebapp2),
], debug=True)
def main():
from paste import httpserver
httpserver.serve(app, host='127.0.0.1', port='8080')
if __name__ == '__main__':
main()
The above code starts a local webserver at port 8080. It might not do exactly what you want, but much is there. You can also run it in appengine.

Related

Flask update html with data from POST

i'm learning Flask/Ajax.
In a POST method i read some data from pwstest.html to run a python script.
Following the Python
#wApp.route("/pwstest",methods=\['GET','POST'\])
def index():
titlepage ='Page title
stato=''
args, data, method = fjrh.handleRequest(request,auth=False)`
if method =='POST':
stato = ''
output = request.get_json()
result = json.loads(output)
logging.info(result)
utente = result\['testoinput'\]
identificativo = result\['numeroinput'\]
dataestrazione = result\['datainput'\]
format='%Y-%m-%d'
dataestrdate = datetime.strptime(dataestrazione,format)
datastr= dataestrdate.strftime("%d-%m-%Y")
parziale= result\['datacheck'\]
if parziale == 'on':`
stringpws = 'http://192.168.x.xxx:5009/plan?diff=True&data=' + datastr
else:
stringpws = 'http://192.168.x.xxx:5009/plan?diff=False&data=01-01-2000'
sqlqry= """select dbo.Callfunction (:1) as result"""
par = (stringpws,)
mApp = MainApp(sql,yyy,mail,walker,parRun, logger)
message= mApp.plan(sqlqry,par)
stato=jsonify(message)
logging.info(stato.status)
return jsonify({"valorestato":message})
else:
return render_template('pwstest.html',nome=titlepage, valorestato=stato)`
And the pwstest.html
<!doctype html>
<html>
<head>
<meta name="description" content="Form di Inserimento di Test">
<meta name="keywords" content="form Inserimento per Test">
<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='main.css') }}">
</head>
<body>
<dt>
<div>
<form class="'form-signin">
<label for="inputtext" class="sr-only">Addetto</label>
<input type="text" name="inputtext" id="inputtext" class="form-control" placeholder="Nome e Cognome" required autofocus>
</form>
<form>
<label for="inputnumber" class="sr-only">Identificativo</label>
<input type="number" name="inputnumber" id="inputnumber" class="form-control" placeholder="Numero Addetto" required autofocus>
</form>
<form>
<label for="inputrec" class="sr-only">Recalc Date</label>
<input type="date" name="inputdate" id="inputdate" class="form-control" placeholder="Recalc from date" required>
</form>
<form>
<label for="inputflag" class="sr-only">Partial</label>
<input type="checkbox" name="inputflag" id="inputflag" class="form-control" placeholder="Partial" required>
</form>
<form>
<button id="btnSignUp" onclick= 'prelievo();' class="btn btn-lg btn-primary btn-block" type="button">Elabora</button>
</form>
</div>
<div id="finale">
{{valorestato}}
</div>
</dt>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
function prelievo() {
const testoinput = document.getElementById("inputtext").value;
const numeroinput = document.getElementById("inputnumber").value;
const datainput = document.getElementById("inputdate").value;
const datacheck = document.getElementById("inputflag").value;
const dict_values = {testoinput, numeroinput,datainput,datacheck}
const s = JSON.stringify(dict_values);
var workingstatus = 'In Elaborazione'
document.getElementById("finale").innerHTML=workingstatus
console.log(s);
$.ajax({
url:"/pwstest",
type:"POST",
contentType: "application/json",
data: JSON.stringify(s)
})
}
When the script return the results, i need to update the Html page with the result.
Seems the return render_template won't works in the POST method.
Could you help me?
Thank you in advance.

Django form is not submitted to the database

I am writing a Django website for dentists, the dentist can register patients with form easily not an issue, however when registering visits for a patient it is not saved, in the admin panel both models works just fine, on the website the visits form dose not save to database.
models.py
from django.db import models
class Paitent(models.Model):
pname = models.CharField(max_length=50)
age = models.IntegerField()
gender = models.CharField(max_length=50)
address = models.CharField(max_length=50)
telephone = models.IntegerField()
mHistory = models.CharField(max_length=500, blank=True, null=True)
def __str__(self):
return self.pname
class Visit(models.Model):
paitent = models.ForeignKey(Paitent,null=True ,on_delete=models.CASCADE, blank=True)
toothNumber = models.CharField('involved tooth', max_length=120)
cComplaint = models.CharField('chief complaint',max_length=120)
sASymptoms = models.CharField('signs and symptoms',max_length=120)
diagnosis = models.CharField(max_length=120)
procedure = models.CharField(max_length=120)
notes = models.TextField(blank=True)
currentVisit = models.DateTimeField(
'time and date of current visit', null=True)
nextAppointment = models.DateTimeField()
def __str__(self):
return self.toothNumber
forms.py
from django import forms
from .models import Paitent
from .models import Visit
class PaitentForm(forms.ModelForm):
class Meta:
model = Paitent
fields = ['pname', 'age', 'gender', 'address', 'telephone']
class VisitForm(forms.ModelForm):
class Meta:
model = Visit
fields = ['paitent', 'toothNumber', 'cComplaint',
'sASymptoms', 'diagnosis', 'procedure',
'notes', 'currentVisit', 'nextAppointment']
views.py
from django.shortcuts import render
from .models import Paitent
from .models import Visit
from .forms import PaitentForm
from .forms import VisitForm
import calendar
from calendar import HTMLCalendar
def homePage(request):
all_paitents = Paitent.objects.all
return render (request, 'homePage.html',{'all':all_paitents})
def newpaitent(request):
if request.method == 'POST':
form = PaitentForm(request.POST or None)
if form.is_valid():
form.save()
return render(request, 'newpaitent.html', {})
else:
return render(request, 'newpaitent.html', {})
def addVisit(request):
if request.method == 'POST':
form = VisitForm(request.POST or None)
if form.is_valid():
form.save()
return render(request, 'addVisit.html', {})
else:
return render(request, 'addVisit.html', {})
template
<!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">
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<link rel="stylesheet" href="../static/css/addVisit.css">
<link href="//db.onlinewebfonts.com/c/e662339992c4abf5b43f537391bd3169?
family=Candara" rel="stylesheet"
type="text/css" />
<title>Add Visit</title>
</head>
<body>
<!-- Title navbar -->
<div class="titleContainer">
<h1> Clinic Name </h1>
<h2> Dental Clinic. </h2>
</div>
<!-- Drop down menu -->
<div class="drop_down_menu hidden buttons_container">
<p id="add_appointment"> Home </p>
<hr id="hr_line">
<p id="calender"> Calender </p>
</div>
<!-- Form -->
<h4 class="h4_text"> Add Current Visit : </h4>
<form class="form_container" method="POST" action="{% url 'addVisit'
%}">
{% csrf_token %}
{{form.as_p}}
<div class="form-group">
<input class="form-control" name="paitent">
</div>
<label> Involved Tooth :</label>
<div class="chart_container form-group">
<div class="chart_item upper_right_quardent">
<option onclick="toothNumber('UR8')">8</option>
<option onclick="toothNumber('UR7')">7</option>
<option onclick="toothNumber('UR6')">6</option>
<option onclick="toothNumber('UR5')">5</option>
<option onclick="toothNumber('UR4')">4</option>
<option onclick="toothNumber('UR3')">3</option>
<option onclick="toothNumber('UR2')">2</option>
<option onclick="toothNumber('UR1')">1</option>
</div>
<div class="chart_item upper_left_quardent">
<option onclick="toothNumber('UL1')">1</option>
<option onclick="toothNumber('UL2')">2</option>
<option onclick="toothNumber('UL3')">3</option>
<option onclick="toothNumber('UL4')">4</option>
<option onclick="toothNumber('UL5')">5</option>
<option onclick="toothNumber('UL6')">6</option>
<option onclick="toothNumber('UL7')">7</option>
<option onclick="toothNumber('UL8')">8</option>
</div>
</div>
<div class="chart_line hidden"> </div>
<div class="chart_line vertical_line hidden"> </div>
<div class="chart_container">
<div class="chart_item lower_right_quardent">
<option onclick="toothNumber('LR8')">8</option>
<option onclick="toothNumber('LR7')">7</option>
<option onclick="toothNumber('LR6')">6</option>
<option onclick="toothNumber('LR5')">5</option>
<option onclick="toothNumber('LR4')">4</option>
<option onclick="toothNumber('LR3')">3</option>
<option onclick="toothNumber('LR2')">2</option>
<option onclick="toothNumber('LR1')">1</option>
</div>
<div class="chart_item lower_left_quardent">
<option onclick="toothNumber('LL1')">1</option>
<option onclick="toothNumber('LL2')">2</option>
<option onclick="toothNumber('LL3')">3</option>
<option onclick="toothNumber('LL4')">4</option>
<option onclick="toothNumber('LL5')">5</option>
<option onclick="toothNumber('LL6')">6</option>
<option onclick="toothNumber('LL7')">7</option>
<option onclick="toothNumber('LL8')">8</option>
</div>
<div class="form-group">
<input type="text" class="form-control" id="toothNumber" name="toothNumber" placeholder="Tooth Number">
</div>
</div>
<div class="non-chart">
<div class="form-group">
<input type="text" class="form-control" id="ccomplain" name="cComplaint" placeholder="Chief Complaint">
</div>
<div class="form-group">
<input type="dropdown" class="form-control" id="sasymptoms" name="sASymptoms" placeholder="Signs and Symptoms">
</div>
<div class="form-group">
<input class="form-control" list="diagnosis" name="diagnosis" placeholder="Diagnosis" />
<datalist id="diagnosis">
<option value="Bad Oral Hygien"></option>
<option value="Gingivitis"></option>
<option value="Periodentits"></option>
<option value="dental Stain"></option>
<option value="dental and Gingival Stain"></option>
<option value="Mobility"></option>
<option value="Superficial Caires"></option>
<option value="Deep Caires"></option>
<option value="Reversible Pulpitis"></option>
<option value="Irreversible Pulpitis"></option>
<option value="Necrotic"></option>
<option value="Retained Root"></option>
</datalist>
</div>
<div class="form-group">
<input class="form-control" list="procedure" name="procedure" placeholder="Procedure" required />
<datalist id="procedure">
<option value="Treatment"></option>
<option value="Scalling and Polishing"></option>
<option value="Deep Scalling and polishing"></option>
<option value="Whitening"></option>
<option value="Direct Pulp Capping"></option>
<option value="Indirect Pulp Capping"></option>
<option value="Amlgam Filling"></option>
<option value="Composite Filling"></option>
<option value="Build Up"></option>
<option value="RCT"></option>
<option value="Crown Preparation"></option>
<option value="Extraction"></option>
</datalist>
</div>
<div class="form-group">
<input class="form-control notes" name="notes" placeholder="Notes"/>
</div>
</div>
<label class="appointment_label"> Current Visit Date :</label>
<div class="form-group appointment">
<input type="datetime-local" class="form-control" id="current_visit" name="currentVisit" required>
</div>
<label class="appointment_label"> Next Appointment :</label>
<div class="form-group appointment">
<input type="datetime-local" class="form-control"
id="appointment"
name="nextAppointment">
</div>
<div class="bottom_button_cotainer">
<a href="javascript:history.back() " class="btn btn-danger button">
cancel </a>
<button type="submit" class="btn btn-primary form-group button">
Submit </button>
</div>
</form>
<script>
function toothNumber(string) {
document.getElementById("toothNumber").value = string;
}
</script>
</body>
</html>
urls:
from django.urls import path
from . import views
urlpatterns = [
path('', views.homePage, name='homePage'),
path('newpaitent', views.newpaitent, name='newpaitent'),
path('calendar', views.calendar, name='calendar'),
path('paitentInfo', views.paitentInfo, name='paitentInfo'),
path('addVisit', views.addVisit, name='addVisit'),
path('paitentInfoSearched', views.paitentInfoSearched,
name='paitentInfoSearched'),
path('visits', views.visits, name='visits')
thank you in advance
If the form is not valid, it wont be committed to database.
Print the form errors, this should help you understand why the form is not getting saved
if form.is_valid():
form.save()
else:
print(form.errors)
I think you didn't provide context in view:
Instead of this:
def addVisit(request):
if request.method == 'POST':
form = VisitForm(request.POST or None)
if form.is_valid():
form.save()
return render(request, 'addVisit.html', {})
else:
return render(request, 'addVisit.html', {})
try this:
def addvisit(request):
if request.method == 'POST':
form = VisitForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect("/") #Add your project route here where you want to go after adding visitors
except:
pass
else:
form = VisitForm()
return render(request, 'addvisit.html', {'form':form})

How to display flask data on URL path

hi I created a simple website to calculate the square of the number. below is the code
calculate.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">
<link rel="stylesheet" href="homepage.css">
<title>Flask </title>
</head>
<body>
<header>
square
</header>
<div class="congrat">
{{ result }}
</div>
</body>
</html>
homepage.html
<form method="post" action="/square">
<div class="calculate">
<b>Square</b><br/>Num
<input type="text" name="number"><br/>
<input type="submit" value="calculate">
</div>
</form>
python
#app.route("/square", methods=['POST'])
def square():
number = request.form["number"]
return render_template("calculate.html", result = int(number) ** 2)
now I want to display input number in URL path. e.g. http://127.0.0.1:3000/square/10
so I've tried this
<form method="post" action="/square/<number>">
<div class="calculate">
<b>Square</b><br/>Num
<input type="text" name="number"><br/>
<input type="submit" value="calculate">
</div>
</form>
#app.route("/square/<number>", methods=['POST'])
def square(number):
number = request.form["number"]
return render_template("calculate.html", result = int(number) ** 2)
but it didn't work. What could I do?
You could get variables directly parsed from Flask URL
#app.route("/square/<number>", methods=['POST'])
def square(number):
return render_template("calculate.html", result = int(number) ** 2)
Edit:
<form id="your_form" method="post" onsubmit="yourFunction()">
<input type="text" name="keywords">
<input type="text" name="number"><br/>
<input type="submit" value="calculate">
</form>
<script>
function yourFunction(){
var action_src = "/square/" + document.getElementsByName("number")[0].value;
var your_form = document.getElementById('your_form');
your_form.action = action_src ;
}
</script>

How can I append data from html to array in views from a button?

I'm trying to build a website that generates a power hour style video from a list of music videos that the user selects by searching through the youtube api. I'm having trouble figuring out how to append selected videos to a list (addedVideos) in view.py from a button (add) in my html. I need to append each added video to a list so I can display them and loop through them in an embedded youtube player. This is my first django project so I don't have a good understanding of what the potential problems could be. index.html and views.py below:
views.py
import requests
from isodate import parse_duration
from django.conf import settings
from django.shortcuts import render, redirect
def index(request):
addedVideos = []
videos = []
if request.method == 'POST':
search_url = 'https://www.googleapis.com/youtube/v3/search'
video_url = 'https://www.googleapis.com/youtube/v3/videos'
search_params = {
'part' : 'snippet',
'q' : request.POST['search'],
'key' : settings.YOUTUBE_DATA_API_KEY,
'maxResults' : 3,
'type' : 'video'
}
#print(request.POST['submit'])
r = requests.get(search_url, params=search_params)
#print(r)
results = r.json()['items']
#print(results)
video_ids = []
for result in results:
video_ids.append(result['id']['videoId'])
if request.POST['submit'] == 'lucky':
return redirect(f'https://www.youtube.com/watch?v={ video_ids[0] }')
video_params = {
'key' : settings.YOUTUBE_DATA_API_KEY,
'part' : 'snippet,contentDetails',
'id' : ','.join(video_ids),
'maxResults' : 3
}
r = requests.get(video_url, params=video_params)
results = r.json()['items']
for result in results:
video_data = {
'title' : result['snippet']['title'],
'id' : result['id'],
'url' : f'https://www.youtube.com/watch?v={ result["id"] }',
'duration' : int(parse_duration(result['contentDetails']['duration']).total_seconds() // 60),
'thumbnail' : result['snippet']['thumbnails']['high']['url']
}
videos.append(video_data)
if request.POST['add'] == 'addValue':
print("add clicked")
context = {
'videos' : videos,
'addedVideos': addedVideos
}
return render(request, 'search/index.html', context)
index.html
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Search YouTube</title>
<!-- Bootstrap core CSS -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link href="{% static 'search/album.css' %}" rel="stylesheet">
</head>
<body>
<main role="main">
<section class="jumbotron text-center">
<div class="container">
<h1 class="jumbotron-heading">Build Your Power Hour</h1>
<p class="lead text-muted">Select music videos to add to your power hour</p>
<form method="POST">
<div class="input-group mb-3">
{% csrf_token %}
<input type="text" name="search" class="form-control" aria-label="Username">
</div>
<p>
<button type="submit" name="submit" value="search" class="btn btn-primary my-2">YouTube Search</button>
<button type="submit" name="submit" value="lucky" class="btn btn-secondary my-2">I'm Feeling Lucky</button>
</p>
</form>
</div>
</section>
<div class="album py-5 bg-light">
<div class="container">
<div class="row">
{% for video in videos %}
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="bd-placeholder-img card-img-top" width="100%" height="225" src="{{ video.thumbnail }}" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: Thumbnail"></img>
<div class="card-body">
<p class="card-text">{{ video.title }}</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<form method="POST">
{% csrf_token %}
<button type="submit" name="add" value="addValue" id='{{ video }}' class="btn btn-sm btn-outline-secondary">Add</button>
</form>
</div>
<small class="text-muted">{{ video.duration }} mins</small>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</main>
</body>
</html>
Running this as is gives a MultiValueDictKeyError at 'q' : request.POST['search'],
Any help would be appreciated, thanks.
You should put / in front of search/index.html instead of search/index.html.
And you don't have to have the https:// you can just put // instead.

Keep user input after press input type="submit" without using JQuery or Ajax

i'm creating a python web application which get multiple user input from input type="number" and calculation will be done when input type="submit" is pressed. I managed to do it but it appears that input that user entered earlier disappear because the page refresh when submitted. Can anyone help me how to keep the user input even after input type="submit" is pressed.
This is my python script:
from flask import Flask, render_template, request
import math
app = Flask(__name__, template_folder='C:\\Users\\iyzadsyammil\\.PyCharmCE2017.1\\config\\fileTemplates')
#app.route('/')
def index():
return render_template('index.html')
#app.route('/Menu')
def showmenu():
return render_template('index.html')
#app.route('/App',methods=['GET', 'POST'])
def showapp():
outpb=0
x=0
logpb=0
error=" "
if request.method=='POST':
ingor = request.form['inGOR']
inog = request.form['inOG']
ingg = request.form['inGG']
inws = request.form['inWS']
intemp = request.form['inT']
inpress = request.form['inP']
innc = request.form['inNC']
cor1 = request.form['cor1']
cor2 = request.form['cor2']
cor3 = request.form['cor3']
cor4 = request.form['cor4']
ingor = float(ingor)
inog = float(inog)
ingg = float(ingg)
inws = float(inws)
intemp = float(intemp)
inpress = float(inpress)
innc = float(innc)
try:
if cor1 == "VB":
if inog <= 30:
outpb = ((27.64*ingor/ingg)*10**((-11.172*inog)/(intemp+460)))**(1/1.0937)
else:
outpb = ((56.06*ingor/ingg)*10**((-10.393*inog)/(intemp+460)))**(1/1.187)
elif cor1 == "AM":
outpb = 0.00538088*ingor**0.715082*ingg**-1.87784*(141.5/(inog+131.5))**3.1437*(intemp+460)**1.32657
elif cor1 == "G":
x = (ingor/ingg)**0.816*((intemp**0.172)/(inog**0.989))
logpb = 1.7669 + 1.7447 * math.log10(x) - (0.30218*(math.log10(x)**2))
outpb = 10**logpb
elif cor1 == "PF":
x = 7.916*(10**-4)*inog**1.541-(4.561*(10**-5)*intemp**1.3911)
outpb = ((112.727*ingor**0.577421)/(ingg**0.8439*10**x))-1391.051
elif cor1 == "S":
outpb = 18.2*((ingor/ingg)**0.83*10**(0.00091*intemp-0.0125*inog)-1.4)
else:
outpb = "Invalid Correlation!!"
except ValueError:
error = "Please enter an appropriate value!"
return render_template('app.html',error=error,outpb=outpb)
if __name__ == "__main__":
app.run(debug=True)
This is my current html page :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Testing Program</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="header">
<nav>
<ul class="nav nav-pills pull-right">
<li role="presentation" class="active">Home
</li>
<li role="presentation" class="active">App
</li>
<li role="presentation" class="active">Log In
</li>
<li role="presentation" class="active">Sign Up
</li>
</ul>
</nav>
<h3 class="text-muted">Experiment</h3>
</div>
<div class="jumbotron">
<h1>WELCOME!!</h1>
</div>
<div class="row marketing">
<form method="POST" class="col-lg-6" >
<h3>PVT Application</h3>
<br>
<table>
<tr><td>Input Data</td><td></td><td></td></tr>
<tr><td>Solution GOR(Rs) </td><td><input type="number" step="any" name="inGOR"></td><td>scf/bbl</td></tr>
<tr><td>Oil Gravity </td><td><input type="number" step="any" name="inOG"></td><td>API</td></tr>
<tr><td>Gas Gravity </td><td><input type="number" step="any" name="inGG"></td><td>gr/cc</td></tr>
<tr><td>Water Salinity </td><td><input type="number" step="any" name="inWS"></td><td>ppm</td></tr>
<tr><td>Temperature </td><td><input type="number" step="any" name="inT"></td><td>◦F</td></tr>
<tr><td>Pressure </td><td><input type="number" step="any" name="inP"></td><td>Psia</td></tr>
<tr><td>Nitrogen Content </td><td><input type="number" step="any" name="inNC"></td><td>%mol</td></tr>
</table>
<br>
<table>
<tr><td>Correlation</td><td></td></tr>
<tr>
<td>Bubble Point Pressure(Pb) </td>
<td>
<select name="cor1">
<option value="none"></option>
<option value="VB">Vasquez and beggs</option>
<option value="AM">Al-Marhoun</option>
<option value="G">Glaso</option>
<option value="PF">Petrosky and Farshad</option>
<option value="S">Standing</option>
</select>
</td>
</tr>
<tr>
<td>Solution GOR(Rs)</td>
<td>
<select name="cor2">
<option value=" "></option>
<option value="VB">Vasquez and beggs</option>
<option value="AM">Al-Marhoun</option>
<option value="G">Glaso</option>
<option value="PF">Petrosky and Farshad</option>
<option value="S">Standing</option>
</select>
</td>
</tr>
<tr>
<td>Oil Formation Volume Factor(Bo) </td>
<td>
<select name="cor3">
<option value=" "></option>
<option value="VB">Vasquez and beggs</option>
<option value="AM">Al-Marhoun</option>
<option value="G">Glaso</option>
<option value="PF">Petrosky and Farshad</option>
<option value="S">Standing</option>
</select>
</td>
</tr>
<tr>
<td>Viscosity(µo) </td>
<td>
<select name="cor4">
<option value=" "></option>
<option value="CC">Chew Connally</option>
<option value="BR">Beggs Robinson</option>
</select>
</td>
<td><input type="submit" value="Calculate"></td>
</tr>
</table>
<br>
<table >
<tr><td>Result</td><td></td></tr>
<tr><td>Pb</td><td>{{outpb}}</td></tr>
<tr><td>Rs(Solution GOR)</td><td></td></tr>
<tr><td>Corrected Pb(Nitrogen Effect)</td><td></td></tr>
<tr><td>Bo</td><td></td></tr>
<tr><td>Co</td><td></td></tr>
<tr><td>µo</td><td></td></tr>
</table>
<!--
<table>
<tr><td>Enter Length (cm) : {{l}}</td><td><input type="number" step="any" name="l"></td></tr>
<tr><td>Enter Width (cm) : {{w}}</td><td><input type="number" step="any" name="w"></td></tr>
<tr><td>Enter Height (cm) : {{h}}</td><td><input type="number" step="any" name="h"></td></tr>
<tr><td><input type="submit" value="Calculate"></td></tr>
</table>
<br/>
</form>
</div>
<footer class="footer">
<p>Copyright © Invigour Energy 2016</p>
</footer>
</div>
</body>
</html>
No jQuery, no Ajax. but obviously you need some JS.
<input id="number" type="number" value="num">
<input id="submit" type="submit" value="submit">
document.getElementById("submit").addEventListener("click", function(){
var val = document.getElementById("number").value
sessionStorage.setItem("number", val);
});
window.onload = function() {
var session_value = sessionStorage.getItem("number") || 0;
document.getElementById("number").value = session_value;
}
If you give some clues that how do you use python (db interaction, templating etc.) another solutions might be considered.
sessionStorage
The <input type="submit"> will reach the action attribute of your <form> when clicked, or will refresh the page if the action is empty.
You can use a <button> element and assign it a function on the click event, for example:
<!-- There is no form needed if you don't need to submit -->
<div id="form">
<input type="number" id="myNumber">
<input type="number" id="myOtherNumber">
<button type="button" id="submit">Calculation</button>
</div>
JS part:
window.onload = function () {
/* get elements */
var num_1 = document.getElementById('myNumber'),
num_2 = document.getElementById('myOtherNumber'),
btn = document.getElementById('submit');
/* do what you want with your number
when the button is clicked */
btn.onclick = function () {
window.console.log(num_1.value + num_2.value);
};
};

Categories