This question already has answers here:
Post values from an HTML form and access them in a Flask view
(2 answers)
Closed 5 years ago.
I have written a html code,which will get the 3 inputs from user.
I have attached html code snippet as follows;
You can give it a try running this code. this code basically accepts 3 values from the user those are team1,team2 and match_id and upon clicking on predict button, I want those value to go in my python script where i have written machine learning algorithm.
<!DOCTYPE html>
<html>
<head>
<title>Criclytics</title>
<link rel="stylesheet" href="bootstrap.min.css">
<script src="bootstrap.min.js"></script>
<script src="jquery.min.js"></script>
<style type="text/css">
#import url(http://fonts.googleapis.com/css?family=Exo:100,200,400);
#import url(http://fonts.googleapis.com/css?family=Source+Sans+Pro:700,400,300);
body{
margin: 0;
padding: 0;
background: #fff;
color: black;
font-family: Arial;
font-size: 25px;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.bcg-img{
width: 100vw;
height: 100vh;
z-index: -1;
position: fixed;
background-image: url("bg-blurred.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
table, td, th {
text-align: center;
}
table {
border-collapse: collapse;
width: 50%;
}
th, td {
padding: 15px;
}
.button1 {width: 250px;}
</style>
</head>
<body>
<div class="bcg-img"></div>
<div class="jumbotron" align="center" style="opacity:0.60">
<h1 align="center"><b>Criclytics</b></h1>
Predicting chances of winning
</div>
<form onsubmit="http://localhost:5000/">
<div class="col-xs-3">
<label for="ex2">Team 1</label>
<input class="form-control" id="team1" id="team1" type="text" placeholder="Enter team 1">
</div>
<div class="col-xs-3">
<label for="ex2">Team 2</label>
<input class="form-control" id="team2" id="team2" type="text" placeholder="Enter team 2">
</div>
<div class="col-xs-3">
<label for="ex2">Match ID:</label>
<input class="form-control" id="matchid" id="matchid" type="number" placeholder="Enter match ID ">
</div>
<br>
<input type="submit" value="Predict" class="btn btn-info btn-lg" style="width: 250px"/>
<!--
<div width="cover" padding="30%"><!--put your graph here</div>-->
</form>
</body>
</html>
I am using flask to create the server on the localhost:5000 and i have written code, as follows;
from flask import Flask, render_template
from flask import request
app = Flask(__name__)
print("hello")
#app.route('/')
def getrender():
return render_template('/cric.html')
#app.route('/',methods=['GET','POST'])
def getinfo():
if request.method == 'GET':
a=request.args.get('team1')
b=request.args.get('team2')
c=request.args.get('matchid')
print(a,b,c)
return a,b,c
if __name__=='__main__':
app.run(debug=True)
html file runs perfectly on localhost:5000 but I dont know how I can access those user input values and use it as input for my machine learining algorithm.
I just want help how to access those team1,team2 and match_id and get them in variables so that i can use them in my program.
You have a problem with your form,
all your input doesn't have a name attribute and instead it has 2 id attributes.
So change one id attribute to name
here is the reason :
Definition and Usage
The name attribute specifies the name of an element.
The name attribute is used to reference elements in a JavaScript, or
to reference form data after a form is submitted.
Note: Only form elements with a name attribute will have their values passed when submitting a form.
Your Form should be like this :
<form method="POST" action="{{url_for('getinfo')}}">
<div class="col-xs-3">
<label for="ex2">Team 1</label>
<input class="form-control" name="team1" id="team1" type="text" placeholder="Enter team 1">
</div>
<div class="col-xs-3">
<label for="ex2">Team 2</label>
<input class="form-control" name="team2" id="team2" type="text" placeholder="Enter team 2">
</div>
<div class="col-xs-3">
<label for="ex2">Match ID:</label>
<input class="form-control" id="matchid" name="matchid" type="number" placeholder="Enter match ID ">
</div>
<br>
<input type="submit" value="Predict" class="btn btn-info btn-lg" style="width: 250px"/>
<!--
<div width="cover" padding="30%"><!--put your graph here</div>-->
</form>
In your views functions, you should have 2 with different URLs: one for the home page and another for form submission
#app.route('/')
def getrender():
return render_template('/cric.html')
#app.route('/predict', methods=['GET', 'POST'])
def getinfo():
if request.method=='POST':
a=request.form.get('team1')
b=request.form.get('team2')
c=request.form.get('matchid')
print(a,b,c)
else :
return 'get Im in '
return 'OK'
My advice:
Assign another route for the html page
#app.route('/cric')
def getrender():
return render_template('/cric.html')
Update method check from GET to POST in function getinfo and use request.form to get the parameter
#app.route('/',methods=['GET','POST'])
def getinfo():
print request.method # print the request.method for debug purpose
if request.method == 'POST':
a=request.form.get('team1')
b=request.form.get('team2')
c=request.form.get('matchid')
print(a,b,c)
return render_template('/cric.html')
And update the form header and assign three input with name in html:
<form action="http://localhost:5000/" method="post">
...
<input class="form-control" id="team1" name="team1" type="text" placeholder="Enter team 1">
...
Then you can visit the '/cric' to view the html page, then submit the form, which will invoke a post request to '/' and print the parameters.
Related
I am trying to create a page to generate passwords and the user will select either level 0 or level 1 for varying strengths of the password. And I am not able to get the users selection of level 0 or level 1 using the radio button.
My views.py
from django.shortcuts import render
import random
import string
from types import NoneType
from random_word import RandomWords
from .forms import CHOICES
def password(request):
passw = passGenAdvanced()
form = CHOICES(request.POST)
if form.is_valid():
selected = form.cleaned_data.get("password")
print(selected)
return render(request, 'generator/password.html', {"password":passw})
My forms.py
from django import forms
password = [('0','Level 0'), ('1', 'Level 1')]
class CHOICES(forms.Form):
password = forms.ChoiceField(choices=password, widget=forms.RadioSelect)
My html file
{% extends 'generator/base.html'%}
{% block content %}
<style>
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
<form method = "POST">
{% csrf_token %}
<div class="form-check">
<input class="form-check-input" type="radio" name="password" id="Level0">
<label class="form-check-label" for="password">Level 0</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="password" id="Level1">
<label class="form-check-label" for="password">Level 1</label>
</div>
<button type="submit" class="button">Submit</button>
</form>
<h5 class="alert alert-success">Your Generated Password: <strong>{{password}}</strong></h5>
{% endblock %}
Sorry if the problem may seem obvious, I am new to django.
After printing out the form.error it keeps saying this "on" it isn't even one of my radio options. So how does it give me that?
The radio inputs are missing the value so add value for each radio and try again.
this is my function that uses google finance api to get news articles.
someapp/views.py
def news(request):
if request.method == 'POST':
url = "https://google-finance4.p.rapidapi.com/ticker/"
querystring = {"t":"ETH-USD","hl":"en","gl":"US"}
headers = {
"X-RapidAPI-Key": "API KEY",
"X-RapidAPI-Host": "google-finance4.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
response.status_code
response.text
response.json()
articles = response.json()['news']
return render(request, 'news.html', {
"article": articles })
else:
return HttpResponse('Error')
this is the html code
<body class="bg-dark">
<div
style="
position: flex;
width: 450px;
align-items: center;
align-content: center;
justify-content: center;
margin: 370px auto;
"
>
<img class ="img-fluid" src="{% load static %} /static/logo.png" "
alt="Crypto Talk"
</div>
<p>**{{ article }}**</p>
</body>
this is the html to the page where the POST request is coming from.
<form
class="form-inline"
method="POST"
action="{{ 'news/' }}"
name="news"
>
<div
class="input-group mb-3"
style="margin: 0 auto; display: flex; width: 450px"
>
{%csrf_token%}
<input
type="text"
class="form-control"
placeholder="Enter Crypto"
name="search"
style="
display: block;
margin: 0 auto;
border-top-left-radius: 0;
border-bottom-right-radius: 0;
border-top-left-radius: 5px;
border-bottom-left-radius: 5px;
"
/>
<button
class="btn btn-outline-primary btn-md"
type="submit"
id="button-addon2"
>
Search
</button>
for some reason it takes me to the new html but the page only has the logo. The content from the api I am looking to return is showing up in my terminal with the error "Not Found: /news/requestProvider.js.map"? is there something wrong with how im using Django's templating language or does it have to do with my views? Ultimately I am trying to render the articles found in the 'news' key when using this api and rendering it just like a google search.
Just needed to change the text color! hahaha.
I am new to Django and I am working on a site which should take user input and use it for further operations. I am using a simple text field and I am trying to access the input using request.POST method, however this is giving MultiValueDictKeyError on the name of the text field.
views.py
from django.shortcuts import render
from django.http import HttpResponse
import openpyxl
import math
def index(request):
if "GET" == request.method:
return render(request, 'index.html')
else:
excel_file = request.FILES["excel_file"]
wb = openpyxl.load_workbook(excel_file)
# getting a particular sheet by name out of many sheets
# USING TEXT BOX
sheet_id = request.POST["leadtime"]
sheet_name = str(sheet_id) + "_Day_Lead"
worksheet = wb["Observed"]
worksheet1 = wb[sheet_name]
index.html
<div class="md:flex flex-col w-full items-center">
<div class="relative mb-4">
<form action="index" method="POST">
{% csrf_token%}
<label for="full-name" class="leading-7 text-sm text-gray-600">Duration of Lead Time in Day(s)</label>
<input type="text" id="full-name" placeholder="1 to 5 or ALL" name="leadtime" class="w-full bg-white rounded border border-gray-300 focus:border-green-500 focus:ring-2 focus:ring-green-200 text-base outline-none text-gray-700 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out">
</form>
</div>
<div class="relative mb-4">
<form action="index" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file"
title="Upload excel file"
name="excel_file"
style="border: 3px solid green ; padding: 5px;"
required="required">
</div>
<button type = "submit" class="flex mx-auto text-white bg-green-500 border-0 py-2 px-8 focus:outline-none hover:bg-green-600 rounded text-lg items-center">Submit</button>
</div>
try this
sheet_id = request.POST.get("leadtime")
Refer https://docs.djangoproject.com/en/3.1/ref/request-response/#querydict-objects
I am trying to interact with my machine learning model where I can get the input value to the flask route method from HTML but not able to pass on the response with a string value to the ajax query.
THe click of the button hits the ajax function and does goto the flask route function, but it doesn't even hit the success or error part of the ajax function.
Gives 405 Method not Allowed error.
127.0.0.1 - - [12/Oct/2020 13:15:17] "POST / HTTP/1.1" 405 -
I am new to Flask and not aware of data binding options. Any help would be appreciated.
HTML PART
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="{{ url_for('static',
filename='css/bootstrap.min.css') }}">
<title>Twitter Sarcasm Detection</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<script src="static/js/signUp.js"></script>
<style>
h1 {
margin-top: 13rem;
color: chocolate
}
p{
margin-top: 36px;
}
.form-group{
margin: 3rem !important;
}
</style>
</head>
<body>
<div class="container" style="text-align:center">
<h1>Twitter Sarcasm Detection</h1>
<p>Enter the text below to find out if its Sarcastic or not!</p>
<form action="http://localhost:5000/" method="post">
<div class="form-group">
<input type="text" class="form-control" id="userText" name="userText">
</div>
<button id="submit" class="btn btn-primary">Submit</button>
<input type="reset" value="Reset" class="btn btn-primary">
<div class="form-group">
<label id="prediction" name="prediction"></label>
</div>
</form>
</div>
AJAX query in the script file
$(function(){
$('#submit').click(function(){
$.ajax({
url: '/predictSarcasm',
data: $('form').serialize(),
type: 'POST',
success: function(response){
$('#prediction').val(response.result);
},
error: function(error){
console.log(error);
}
});
});
});
FLASK Code
from flask import Flask, render_template, json
from joblib import load
pipeline = load("text_classification.joblib")
def requestResults(text):
tweet = pipeline.predict([text])
if tweet == 0:
return "Not-Sarcastic"
else:
return "Sarcastic"
app = Flask(__name__)
#app.route("/")
def home():
return render_template('Index.html')
#app.route('/predictSarcasm', methods=['POST'])
def predictSarcasm():
text = request.form['userText']
prediction = requestResults(text)
return json.dumps({'status':'OK','result':str(prediction)});
if __name__ == "__main__":
app.run(debug=False)
you don't need to use forms for ajax
Html Code
<h1>Twitter Sarcasm Detection</h1>
<p>Enter the text below to find out if its Sarcastic or not!</p>
<div class="form-group">
<input type="text" class="form-control" id="userText" name="userText">
</div>
<button id="submit" class="btn btn-primary">Submit</button>
<input type="reset" value="Reset" class="btn btn-primary">
<div class="form-group">
<label id="prediction" name="prediction"></label>
</div>
</div>
Ajax Code
$('#submit').click(function(){
$.ajax({
url: '/predictSarcasm',
contentType: "application/json",
data: JSON.stringify({ "text": $('#userText').val()})
type: 'POST',
success: function(response){
$('#prediction').val(response.result);
},
error: function(error){
console.log(error);
}
});
});
Python Code
from flask import jsonify
#app.route('/predictSarcasm', methods=['POST'])
def predictSarcasm():
json= request.get_json()
text=json["text"]
prediction = requestResults(text)
return jsonify({"status":"OK",'result':str(prediction)})
I am trying to log on to a website using python and the requests library. I am having some difficulties getting the authenticity keys to work, as they are not specified in the format usually found in other questions here. The HTML markup for the login page is given here:
<html>
<head>
<title>OnLogger</title>
<link rel="stylesheet" href="/jottonia/stylesheet.css" type="text/css">
</head>
<body bgcolor="#FFFFFF">
<img src="/jottonia/gfx/midaslogo.gif">
<p> </p>
<h1>Log in to Jottonia</h1>
<form action="OnLogger" method="POST">
<table class="formtable">
<tbody>
<tr>
<th>Username (e-mail)</th>
<td>
<input size="10" name="email" value="" data-keeper-edited="yes" data-keeper-lock-id="k-iw0hz0yr8pm">
<keeper-lock id="k-iw0hz0yr8pm" style="filter: grayscale(100%); top: 209.156px; left: 367px; z-index: 1; visibility: hidden;"></keeper-lock>
</td>
</tr>
<tr>
<th>Password</th>
<td>
<input type="PASSWORD" name="password" size="10" data-keeper-lock-id="k-5db0syl9lsj" data-keeper-edited="yes">
<keeper-lock id="k-5db0syl9lsj" style="filter: grayscale(100%); top: 240.156px; left: 367px; z-index: 1; visibility: hidden;"></keeper-lock>
</td>
</tr>
</tbody>
</table>
<p><input type="SUBMIT" value="Enter" name="button"> <input type="SUBMIT" value="Mail me the password again" name="button"></p>
</form>
<style>input[data-keeper-lock-id="k-5db0syl9lsj"]:not(:hover) ~ keeper-lock#k-5db0syl9lsj {animation-name: hide-lock; animation-duration: .5s;}
input[data-keeper-lock-id="k-iw0hz0yr8pm"]:not(:hover) ~ keeper-lock#k-iw0hz0yr8pm {animation-name: hide-lock; animation-duration: .5s;}
</style>
</body>
</html>
The interesting regions are <input size="10" name="email" value="" data-keeper-edited="yes" data-keeper-lock-id="k-iw0hz0yr8pm"> and <input type="PASSWORD" name="password" size="10" data-keeper-lock-id="k-5db0syl9lsj" data-keeper-edited="yes">.
I am assuming that the data-keeper-lock-id is some form of authenticity key, and this key is indeed randomly generized each time I reload the page. However, the keys for the email and password are different, and the don't follow the "name"/"value" format that I've seen before. Extracting the values I should be able to do with regular expressions and some clever indexing, but how should I give this when using requests.post? My login info is stored in a dictionary:
myemail = "my#email.com"
mypassword = "1234"
login_info = {"email": myemail, "password": mypassword}
But I thought that requests.post looks for the "name" tag in order to pass the login info?