Updating the same site with Python's Flask module - python

Background:
I'm fairly new to developing front end and the Flask module in Python. I am difficulty updating the same page.
What I want to achieve:
There are three parts to what I want to achieve
Part/Step 1: I can create a form such as the one below
Part/Step 2: When the form is filled in as below, and the [verify] button is hit it goes to Step 3
Part/Step 3: Once the verify button is hit, just underneath it the information that was passed gets placed underneath it. There are also two buttons, with [commit] and [cancel] button. If [cancel] is hit, the site resets to as it were in Step 1. If [commit] is hit, it goes to a different website in step 4
Part/Step 4: If [commit] is hit from the image above, another site is retrieved with the following message.
Note:
Happy to share my code, but I just have the empty form in step 1. I can't proceed after that. As mentioned, I'm very new to front end stuff.
Update:
I'm having difficulties with 2 things currently:
When I click [cancel], the whole form shifts to the left (How can I make it centered?)
How can I print multiple things (ideally in a centered table) after hitting the [verify] button
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
document.getElementById("verify").style.display = "none";
document.getElementById("committed").style.display = "none";
})
function onVerify() {
document.getElementById("verifyName").innerHTML = 'First Name: ' + document.getElementById("first_name").value
document.getElementById("verify").style.display = "block";
}
function onCommit() {
document.getElementById("form").style.display = "none";
document.getElementById("verify").style.display = "none";
document.getElementById("committed").style.display = "block";
}
function onCancel() {
document.getElementById("form").style.display = "block";
document.getElementById("verify").style.display = "none";
document.getElementById("name").value = ""
}
</script>
<style>
h3 {text-align: center;}
.right {
text-align: right;
margin-right: 1em;
}
.center {
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<h3>Personnel Details</h3>
<div class="center" id="form">
<table>
<tr>
<td class="right">
<label>Salutation:</label>
</td>
<td>
<select name="gender">
<option value=""></option>
<option value="male">Mr.</option>
<option value="female">Ms.</option>
</select>
</td>
</tr>
<tr>
<td class="right">
<label>First Name:</label>
</td>
<td>
<input id="first_name">
</td>
</tr>
<tr>
<td class="right">
<label>Middle Name:</label>
</td>
<td>
<input id="middle_name">
</td>
</tr>
<tr>
<td class="right">
<label>Last Name:</label>
</td>
<td>
<input id="last_name">
</td>
</tr>
<tr>
<td class="right">
<label>Email:</label>
</td>
<td>
<input id="email">
</td>
</tr> <tr>
<td class="right">
<label>DOB:</label>
</td>
<td>
<input type="date" name="issue_date" value="" min="1900-01-01" max="2100-12-31">
</td>
</tr>
<tr>
<td>
</td>
<td class="center">
<div>
<button onclick="onVerify()">Verify</button>
</div>
</td>
</tr>
</table>
</div>
<div id="verify">
<div id="verifyName">
</div>
<button onclick="onCommit()">Commit</button>
<button onclick="onCancel()">Cancel</button>
</div>
<div id="committed">
Committed! :)
</div>
</html>

This is just the minimal code, I have used to just give an idea, how to achieve the similar behavior, with just one input field. You can easily extend this with other fields.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
document.getElementById("verify").style.display = "none";
document.getElementById("committed").style.display = "none";
})
function onVerify() {
document.getElementById("verifyName").innerHTML = 'First Name: ' + document.getElementById("name").value
document.getElementById("verify").style.display = "block";
}
function onCommit() {
document.getElementById("form").style.display = "none";
document.getElementById("verify").style.display = "none";
document.getElementById("committed").style.display = "block";
}
function onCancel() {
document.getElementById("form").style.display = "block";
document.getElementById("verify").style.display = "none";
document.getElementById("name").value = ""
}
</script>
<div id="form">
<label> First Name:
<input id="name">
</label>
<div>
<button onclick="onVerify()">Veryfy</button>
</div>
</div>
<div id="verify">
<div id="verifyName">
</div>
<button onclick="onCommit()">Commit</button>
<button onclick="onCancel()">Cancel</button>
</div>
<div id="committed">
Committed! :)
</div>

Related

Missing columns in final html table after rendering the pandas dataframe to html

I am writing the below df values into a html template. I am missing chemistry and algebra column in the final output html table.
import pandas as pd
df = pd.DataFrame({'name': ['Somu', 'Kiku', 'Amol', 'Lini'],
'physics': [68, 74, 77, 78],
'chemistry': [84, 56, 73, 69],
'algebra': [78, 88, 82, 87]})
df_html = df.to_html()
template_vars = { "html_table":df_html}
f = open(output.html, 'w', encoding='utf-8')
html_template ="metrics.html"
temp = Template(open(html_template, 'r').read())
template = temp.render(template_vars)
f.write(template)
f.close()
In the below Metrics.html has 4 buttons, out of which 2nd button is not showing up all the columns.
Metrics.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<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">
<style>
#incorrect-response-panel .panel{
border-radius: 0;
}
.response-panel-title {
font-weight: normal;
}
.doc-info h3 {
font-weight: normal;
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.collapsible {
background-color: #777;
color: white;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
.active, .collapsible:hover {
background-color: #555;
}
.collapsible:after {
content: '\002B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
</style>
</head>
<body>
<button id=button1 type="button" class="collapsible">Top 1 Correct answer </button>
<div class="content">
{{correct_tab1}}
</div>
<div>
</br> </br>
</div>
<button id=button2 type="button" class="collapsible">Top 1 Incorrect answer </button>
<div class="content">
{{html_table}}
</div>
<div>
</br> </br>
</div>
<button id=button3 type="button" class="collapsible">Top 1 Correct answer </button>
<div class="content">
{{correct_tab1}}
</div>
<div>
</br> </br>
</div>
<button id=button4 type="button" class="collapsible">Top 1 Incorrect answer </button>
<div class="content">
{{incorrect_tab1}}
</div>
<div>
</br> </br>
</div>
https://codepen.io/code_rev/pen/VwKBpRY
As I testing your code partly after romoving () in (df=) and (`df_html=) in your qustion:
import pandas as pd
df = pd.DataFrame({'name': ['Somu', 'Kiku', 'Amol', 'Lini'],
'physics': [68, 74, 77, 78],
'chemistry': [84, 56, 73, 69],
'algebra': [78, 88, 82, 87]})
df_html = df.to_html()
we find the content of df_html is (just reformating):
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>name</th>
<th>physics</th>
<th>chemistry</th>
<th>algebra</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>Somu</td>
<td>68</td>
<td>84</td>
<td>78</td>
</tr>
<tr>
<th>1</th>
<td>Kiku</td>
<td>74</td>
<td>56</td>
<td>88</td>
</tr>
<tr>
<th>2</th>
<td>Amol</td>
<td>77</td>
<td>73</td>
<td>82</td>
</tr>
<tr>
<th>3</th>
<td>Lini</td>
<td>78</td>
<td>69</td>
<td>87</td>
</tr>
</tbody>
</table>
so we find the complete DataFrame with all the columns.
Hence, this part of the code is correct (after removing the character (`) I mentioned above).
The only suspicious sentence, in my thought, is
template = temp.render(template_vars)
which depneds on html_template ="metrics.html" and template_vars = { "html_table":df_html}
Therefore, if there is a problem still existed, it would be necessary to add 'metrics.html`. we may find something.
Extending
In the 'metrics.html` you uploaded, I have changed the following part:
<button id=correct1 type="button" class="collapsible">Correct answer </button>
<div class="content">
{{correct_tab1}}
</div>
<div>
</br> </br>
</div>
<button id=incorrect1 type="button"
to
<button id=correct1 type="button" class="collapsible">Correct answer </button>
<div class="content">
{{html_table}} <!-- to match your question -->
</div>
<div>
</br> </br>
</div>
then after running your code, the rendered part in output.html related to the table we intend is:
<button id=incorrect1 type="button" class="collapsible"> Incorrect answer </button>
<div class="content">
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>name</th>
<th>physics</th>
<th>chemistry</th>
<th>algebra</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>Somu</td>
<td>68</td>
<td>84</td>
<td>78</td>
</tr>
<tr>
<th>1</th>
<td>Kiku</td>
<td>74</td>
<td>56</td>
<td>88</td>
</tr>
<tr>
<th>2</th>
<td>Amol</td>
<td>77</td>
<td>73</td>
<td>82</td>
</tr>
<tr>
<th>3</th>
<td>Lini</td>
<td>78</td>
<td>69</td>
<td>87</td>
</tr>
</tbody>
</table>
</div>
<div>
</br> </br>
</div>
so we notice that {{html_table}} we replaced correctly with HTML code of the table including all the columns.
so I do not find any problem.
I guess, you may investigate an old version of output.html and the generated one is in another folder.
or as it is clear, you did not upload the 'metrics.html` you work with, since the uploaded one does not contain the HTML you added in your question

Python Requests, Successful website log in but redirects me to log in page

I am trying to scrape a website using Python's Requests Module
It's a website we can only access inside our company.
Every time I try to scrape the website using get(), it show's this
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Authorization Required</title>
</head><body>
<h1>Authorization Required</h1>
<p>This server could not verify that you
are authorized to access the document
requested. Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
<hr>
<address>Apache/2.2.13 (Red Hat) Server at tcfabcert Port 80</address>
</body></html>
But when I insert the auth=('user','pass'), it get's a respone of 200 but it doesn't log me in and every time I try to log in using post() method it just keeps redirecting me to the same Login Page.
Here is my code:
import requests
payload = {'userID': 'user',
'password': 'mypass',
'userLocale': 'US CA',
'userBU': 'MB',
'servName': 'Certification',
'login': 'Login',
'rememberFlag': 'false',
'hiddenHost': 'cpc44743'}
cookie = {'Cookie': 'JSESSIONID=AF1A7CC747492C3D4259B230A5F7635A.PKYCUbG8Dba7VqoxAzD4WA'}
header = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'en-US,en;q=0.9',
'Cache-Control':'max-age=0',
'Connection':'keep-alive',
'Content-Length':'138',
'Content-Type':'application/x-www-form-urlencoded',
'Cookie':'JSESSIONID=AF1A7CC747492C3D4259B230A5F7635A.PKYCUbG8Dba7VqoxAzD4WA',
'Host':'tcfabcert',
'Origin':'http://tcfabcert',
'Referer':'http://tcfabcert/ws/ess/default.jsp',
'Upgrade-Insecure-Requests':'1',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}
with requests.Session() as r:
url = "http://tcfabcert/ws/ess/"
res = r.get(url, auth=('user', 'password')).text
res2 = r.post(url, auth=('user', 'password'), datas=payload, headers=header, allow_redirects=True)
Here is the code of the log in page
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="GENERATOR"
content="IBM WebSphere Page Designer V3.5.2 for Windows" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>Editorial System</title>
<link rel="stylesheet" type="text/css" href="/ws/ess/theme/Style2.css" />
<script type="text/javascript">
var GB_ROOT_DIR = "/ws/ess/greybox/";
</script>
<script type="text/javascript" src="/ws/ess/greybox/AJS.js"></script>
<script type="text/javascript" src="/ws/ess/greybox/AJS_fx.js"></script>
<script type="text/javascript" src="/ws/ess/greybox/gb_scripts.js"></script>
<link href="/ws/ess/greybox/gb_styles.css" rel="stylesheet" type="text/css" media="all" />
<script language="JavaScript1.2">
<!-- Hide from older browsers
// Original JavaScript code by Duncan Crombie: dcrombie at chirp.com.au
// Please acknowledge use of this code by including this header.
function getCookie(name) { // use: getCookie("name");
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
var today = new Date();
var expiry = new Date(today.getTime() + 28 * 24 * 60 * 60 * 1000); // plus 28 days
function setCookie(name, value) { // use: setCookie("name", value);
document.cookie=name + "=" + escape(value) + "; expires=" + expiry.toGMTString();
}
// Stop hiding -->
function dispHandle(obj) {
if (obj.style.display == "none")
obj.style.display = "";
else
obj.style.display = "none";
}
</script>
<script language="JavaScript1.2">
function rememberMe(cbox)
{
userIDValue = document.forms(0).userID.value;
userPWDValue = document.forms(0).password.value;
userLocale = document.forms(0).userLocale.value;
userBU = document.forms(0).userBU.value;
if (cbox.checked)
{
document.forms(0).rememberFlag.value = "true";
setCookie("userID", userIDValue);
setCookie("userPWD", userPWDValue);
setCookie("userLocale", userLocale);
setCookie("userBU", userBU);
}
}
//function to reset the locale/bu
function setUserLocale(userLocale, userBU)
{
setCookie("userBU", userBU);
setCookie("userLocale", userLocale);
document.forms(0).submit();
}
function submitForm() {
userIDValue = new String();
userIDValue = document.forms(0).userID.value;
userPWDValue = document.forms(0).password.value;
userLocale = document.forms(0).userLocale.value;
userBU = document.forms(0).userBU.value;
rFlag = document.forms(0).rememberFlag.value;
if (document.forms(0).password.value.length <1)
{
//alert("Please enter password");
//alert("Please enter password");
}
else if (rFlag = "true")
{
setCookie("userID", userIDValue);
setCookie("userPWD", userPWDValue);
setCookie("userLocale", userLocale);
setCookie("userBU", userBU);
}
document.forms(0).submit();
}
function _HpbJumpURL(url)
{
if (url != '')
{
window.location = url;
}
}
function checkBrowser(){
var userID=getCookie("userID");
var userPWD = getCookie("userPWD");
var userLocale = getCookie("userLocale");
var userBU = getCookie("userBU");
if (userID != null && userPWD != null)
{
document.forms(0).userID.value = userID;
document.forms(0).password.value = userPWD;
}
this.ver=navigator.appVersion
this.dom=document.getElementById?1:0
//Changes made by ANANDA5 for IE8 Migration
//this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom)?1:0;
this.ie8=(this.ver.indexOf("MSIE 8")>-1 && this.dom)?1:0;
//End
var hName= window.location.host;
var hPlatform = "";
if (hName.indexOf("cert") != -1 )
{
hPlatform = "Certification";
}
else if (hName.indexOf("prod") != -1)
{
hPlatform = "Production";
}
else if (hName.indexOf("int") != -1)
{
hPlatform = "Development";
}
else if (hName.indexOf("lngcentral") != -1)
{
hPlatform = "Production";
}
else
{
hPlatform = "Development";
}
document.login.servName.value=hPlatform;
return this
}
function addToFavorites()
{
window.external.AddFavorite(window.url, "EdSched");
}
function showNew()
{
var userBU = getCookie("userBU");
if (userBU != null && userBU != "LNFR")
{
var newPage=getCookie("newPage3-17");
if (newPage == null || newPage=="TRUE")
{
whatsNew =GB_showFullScreen("What's new for this Release","../whatsnew.jsp");
}
}
}
</script>
</head>
<body onload="checkBrowser(); showNew();">
<form name="login" method="post" action="/ws/ess/default.jsp"><!-- Set the Default Locale -->
<br>
<br>
<br>
<center>
<table style='background: #dae0d2 url("images/bg.gif") repeat-x bottom; border: 1px thin'>
<tbody>
<tr>
<td align="center"><img src="/ws/ess/images/edsched.png" border="0"></td>
</tr>
<tr>
<td align="center"><label class="TextLabel4">(Editorial Scheduling System)</label> <br>
<br>
</td>
</tr>
<tr>
<td align="center"><label class="TextLabel4">Enter the Login Details</label> <br>
</td>
</tr>
</tbody>
</table>
</center>
<center>
<table style='background: #dae0d2 url("images/bg.gif") repeat-x bottom; border: 1px thin'>
<tbody>
<tr>
<td>
<div id="userDetails">
<center>
<table>
<tbody>
<tr class="EbTopBar">
</tr>
<tr class="EbTopBar">
<td align="right" width="100"><label class="TextLabel1">UserId :</label></td>
<td width="110"><input type="text" name="userID" value=""
class="EbInputBg" size="15" tabindex="1"></td>
</tr>
<tr class="EbTopBar">
<td align="right" width="100"><label class="TextLabel1">Password :</label></td>
<td width="110"><input type="password" name="password" value=""
class="EbInputBg" size="15" tabindex="2"></td>
</tr>
</tbody>
</table>
</center>
</div>
</td>
</tr>
<tr>
<td>
<div style="display:" id="vanisher">
<center>
<table>
<tbody>
<tr class="EbTopBar">
<td align="right" width="100"><label class="TextLabel1">Location</label></td>
<td width="110"><select id="userLocale" name="userLocale"
class="ComboBox_ID12">
<OPTION value="US CA" >US CA</OPTION>
<OPTION value="FR" >FR</OPTION>
<OPTION value="AU" >AU</OPTION>
<OPTION value="SNG" >SNG</OPTION>
<OPTION value="LNC" >LNC</OPTION>
</select></td>
</tr>
<tr class="EbTopBar">
<td align="right" width="100"><label class="TextLabel1">Business Unit</label></td>
<td width="110"><select id="userBU" name="userBU"
class="ComboBox_ID12">
<OPTION value="LNC" >LNC</OPTION>
<OPTION value="COS" >COS</OPTION>
<OPTION value="MI" >MI</OPTION>
<OPTION value="MB" >MB</OPTION>
<OPTION value="MDC-SNG" >MDC-SNG</OPTION>
<OPTION value="LNFR" >LNFR</OPTION>
</select></td>
</tr>
<tr class="EbTopBar">
<td/>
<td align="left" width="100"><label class="TextLabel1">Correct business unit must be selected</label></td>
</tr>
</tbody>
</table>
</center>
</div>
</td>
</tr>
<!--
<TR>
<TD CLASS="link"><A HREF="javascript:dispHandle(vanisher)">Choose
Language </A></TD>
</TR>
-->
<tr>
<td>
<center>
<table>
<tbody>
<tr>
<td align="right" width="100"><label class="TextLabel1">Platform :</label></td>
<td width="110"><input type="text" name="servName" value=""
class="EbReadOnly" size="15" tabindex="3" readonly></td>
</tr>
<tr>
<td align="right" width="100"></td>
<!--
<TD WIDTH="110"><INPUT TYPE="checkbox" NAME="rememberme" VALUE="N"
ONCLICK="rememberMe(this);"><LABEL CLASS="TextLabel1">Remember Me</LABEL></TD>
-->
</tr>
</tbody>
</table>
</center>
</td>
</tr>
<tr>
<td>
<center>
<table id="loginButtons">
<tbody>
<tr>
<td width="80"></td>
<td><input type="submit" name="login"
value='Login'
onclick="submitForm()" class="EbButton" /></td>
<td><input type="reset" name="cancel"
value='Cancel' class="EbButton" /></td>
<td width="80"></td>
</tr>
</tbody>
</table>
</center>
</td>
</tr>
</tbody>
</table>
</center>
<input type="hidden" name="rememberFlag" value="false">
<center>Login problems?<br>
</center>
<center>
<table border="1">
<tbody align="center">
<tr>
<td align="center">English</td>
<td align="center"><a href="javascript:setUserLocale('FR', 'LNFR')";>Français</a></td>
</tr>
</tbody>
</table>
</center>
<input name="hiddenHost" type="hidden" value='cpc44743'/>
</form>
</body>
</html>

Upload unknown numbers (dynamically decided) of files under Django framework

I encountered an issue: if I want to apply this dynamically rows adding bootstrap code(ref here bootstrap) , I won't be knowing how many files user will upload in advance.(Although I define a maximum of numbers of files allowed to be uploaded:10)
I am using Django 2.1.5.
I have tried to write something like UploadFileForm in form.py, but in that way, I needed to write exactly 10 form.Charfield inside the class, which I am not willing to see.
<form action="" method="post" enctype="multipart/form-data" id="bookform">
{% csrf_token %}
<table id="createBookTable" class=" table order-list">
<thead>
<tr>
<td>book title(in original lang.)</td>
<td>author(in original lang.)</td>
<td>book title(in Eng.)</td>
<td>author(in Eng.)</td>
<td>book image</td>
</tr>
</thead>
<tbody>
<tr style="display:none">
<td colspan="5" style="text-align: left;" >
<input type="text" id="counter" name="counter" value=""/>
</td>
</tr>
<tr class="bookTr" id="bookTr-0">
<td class="col-sm-3">
<input type="text" name="orginBookname0" class="form-control" />
</td>
<td class="col-sm-3">
<input type="mail" name="originAuthor0" class="form-control"/>
</td>
<td class="col-sm-3">
<input type="text" name="engBookname0" class="form-control"/>
</td>
<td class="col-sm-3">
<input type="text" name="engAuthor0" class="form-control"/>
</td>
<td>
<input type="file" name="bookimg0">
</td>
<td class="col-sm-1"><a class="deleteRow"></a>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
<tr>
<td colspan="5" style="text-align: left;">
<input type="submit" name="button" id="bookSubmitBtn" class="btn btn-lg btn-block btn-beautiful" value="Submit">
</td>
</tr>
</tfoot>
</table>
</form>
These are modified version of the mentioned bootstrap demo example:
var counter = 0;
$("#counter").prop('value',counter);
$("#addrow").on("click", function () {
if(counter<=9){
counter++;
var newRow = $('<tr class="bookTr" id="bookTr-'+counter+'">');
var cols = "";
cols += '<td><input type="text" class="form-control" name="orginBookname' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="originAuthor' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="engBookname' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="engAuthor' + counter + '"/></td>';
cols += '<td><input type="file" name="bookimg' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
$("#counter").prop('value',counter);
}
else{
alert("You can only add 10 books per time.");
}
});
The expected results would be that all files chosen by the users be uploaded to media\photos folder. Again, we are not able to know in advance how many files they will be uploading.
I want to use ajax call at the front-end under Django framework.
I think you are looking for Formsets. You use django formset to dynamically render and upload any number of form fields. check it out here https://github.com/elo80ka/django-dynamic-formset
I found a way to avoid using form.py but using ajax call.
In settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
In urls.py
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In models.py
class book(models.Model):
titleOrigin = models.CharField(max_length=200,null = False)
authorOrigin = models.CharField(max_length=100,null = True)
titleEnglish = models.CharField(max_length=200,null = True)
authorEnglish = models.CharField(max_length=100,null = True)
bookImgFname = models.CharField(max_length=300,null=True)
In createbook.js(use FormData() function!!!):
function upload(event) {
event.preventDefault();
var formdata = new FormData($('#bookform').get(0));
$.ajax({
url: '/createbook/',
type: 'post',
data: formdata,
cache: false,
processData: false,
contentType: false,
success: function(data) {
alert('success');
}
});
return false;
}
$(function() {
$('#bookform').submit(upload);
});
In views.py, use FileSystemStorage and request.FILES['bookimg'+str(i)](thanks to this tutorial)
def createbook(request):
if request.method == 'POST' and request.is_ajax():
for i in range(int(request.POST.get('counter'))+1): **#the nondisplayed counter is a trick**
curOrginBookname = request.POST.get('orginBookname'+str(i))
curOriginAuthor = request.POST.get('originAuthor'+str(i))
curEngBookname = request.POST.get('engBookname'+str(i))
curEngAuthor = request.POST.get('engAuthor'+str(i))
curBookimg = request.FILES['bookimg'+str(i)]
fss = FileSystemStorage()
concatenatedFname = curOrginBookname+"_"+curBookimg.name
fss.save("photos\\"+concatenatedFname, curBookimg)
bookToBeSaved = book(titleOrigin=curOrginBookname,authorOrigin=curOriginAuthor,
titleEnglish=curEngBookname,authorEnglish=curEngAuthor,bookImgFname=concatenatedFname)
bookToBeSaved.save()
return HttpResponse('')
else:
return render(request, "createbook.html", locals())
remember to import this:
from django.core.files.storage import FileSystemStorage

Get the value from flask html to python

Given below the html code I have created flask server using python. Here I'm
taking only checkboxSelectCombo and after selecting the checkboxes in the flask UI, I want to print those values in python as I click on any flask button.
How to get and print that values in the python?
If anyone knows the answer please help me out.
Thank you
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OPTIMIZATION</title>
<title></title>
<!-- Ignite UI Required Combined CSS Files -->
<link href="http://cdn-na.infragistics.com/igniteui/2018.1/latest/css/themes/infragistics/infragistics.theme.css" rel="stylesheet" />
<link href="http://cdn-na.infragistics.com/igniteui/2018.1/latest/css/structure/infragistics.css" rel="stylesheet" />
<script src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.8.3.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<!-- Ignite UI Required Combined JavaScript Files -->
<script src="http://cdn-na.infragistics.com/igniteui/2018.1/latest/js/infragistics.core.js"></script>
<script src="http://cdn-na.infragistics.com/igniteui/2018.1/latest/js/infragistics.lob.js"></script>
</head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
background-color: #dddddd;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 1px;
}
</style>
<body bgcolor="#a9d284">
<img src="/static/images/logo.gif" alt="Related Book 1" width="300" height="80" align="right">
<script src="/static/scripts.js" charset="utf-8"></script>
<h1>PORTFOLIO OPTIMIZATION</h1>
<style>
.combo-label {margin-bottom:.5em;}
</style>
<form method="POST" action="">
<h4 class="combo-label">SELECT THE STOCK OPTIONS</h4>
<div id="checkboxSelectCombo"></div>
<br><br>
<h4>SELECT THE INPUT DATE</h4>
<input type="date" name="date1" placeholder="Start date">
<input type="date" name="date2" placeholder="End date">
<br><br>
<h4>ENTER CONSTRAINTS CRITERIA</h4>
<table>
<tr>
<th> </th>
<th>Cheap</th>
<th>Moderate</th>
<th>Expensive</th>
<th>PUT</th>
<th>CALL</th>
<th>Not Recommended</th>
<th>Highly Liquid</th>
<th>Moderately Liquid</th>
<th>Less Liquid</th>
<th>MPO</th>
<th>PO</th>
<th>LPO</th>
</tr>
<tr>
<td>Group_Min</td>
<td class="td"><input type="text" name="min1"/></td>
<td class="td"><input type="text" name="min2" /></td>
<td class="td"><input type="text" name="min3"/></td>
<td class="td"><input type="text" name="min4"/></td>
<td class="td"><input type="text" name="min5"/></td>
<td class="td"><input type="text" name="min6"/></td>
<td class="td"><input type="text" name="min7"/></td>
<td class="td"><input type="text" name="min8"/></td>
<td class="td"><input type="text" name="min9"/></td>
<td class="td"><input type="text" name="min10"/></td>
<td class="td"><input type="text" name="min11"/></td>
<td class="td"><input type="text" name="min12"/></td>
</tr>
<tr>
<td>Group_Max</td>
<td class="td"><input type="text" name="max1"/></td>
<td class="td"><input type="text" name="max2"/></td>
<td class="td"><input type="text" name="max3"/></td>
<td class="td"><input type="text" name="max4"/></td>
<td class="td"><input type="text" name="max5"/></td>
<td class="td"><input type="text" name="max6"/></td>
<td class="td"><input type="text" name="max7"/></td>
<td class="td"><input type="text" name="max8"/></td>
<td class="td"><input type="text" name="max9"/></td>
<td class="td"><input type="text" name="max10"/></td>
<td class="td"><input type="text" name="max11"/></td>
<td class="td"><input type="text" name="max12"/></td>
</tr>
</table>
<br><br>
<input type="submit" value="GET RESULTS">
</form>
<script>
var colors = [
{ Name: "FP FP Equity" },
{ Name: "SAN FP Equity" },
{ Name: "NOK1V FH Equity" },
{ Name: "SAN SQ Equity" },
{ Name: "EOA GY Equity" },
{ Name: "SIE GY Equity" },
{ Name: "ENI IM Equity" },
{ Name: "UC IM Equity" },
{ Name: "INGA NA Equity" },
{ Name: "TEF SQ Equity" },
{ Name: "BNP FP Equity" },
{ Name: "BBVA SQ Equity" },
{ Name: "ALV GY Equity" }
];
$(function () {
$("#singleSelectCombo").igCombo({
width: 300,
dataSource: colors,
textKey: "Name",
valueKey: "Name",
dropDownOnFocus: true,
dropDownOrientation: "bottom"
});
$("#multiSelectCombo").igCombo({
width: 300,
dataSource: colors,
textKey: "Name",
valueKey: "Name",
multiSelection: {
enabled: true
},
dropDownOrientation: "bottom"
});
$("#checkboxSelectCombo").igCombo({
width: 300,
dataSource: colors,
textKey: "Name",
valueKey: "Name",
multiSelection: {
enabled: true,
showCheckboxes: true
},
dropDownOrientation: "bottom"
});
});
</script>
</body>
</html>
<!doctype html>
<title>Simple tables</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">
<div class=page>
<h2>OPTIMIZED VALUES</h2>
{% for table in tables %}
<h3>{{titles[loop.index]}}</h3>
{{ table|safe }}
{% endfor %}
</div>
Python backend code
from flask import Flask, render_template, request
from optimization_excel.app import rough_bkend as r1
app = Flask(__name__)
#app.route('/opt')
def index():
return render_template('rough_portopt.html')
#app.route('/opt', methods=['POST'])
def opt():
val = request.form.getlist('checkboxSelectCombo')
print(val)
res1, res2, res3 = r1.get_res1()
return render_template('rough_portopt.html', tables=[res1.to_html(), res2.to_html()],
titles=['na', 'Test Results', 'Constraint values'])
if __name__ == "__main__":
app.run(debug=True)
So I place import pdb; pdb.set_trace() right before your print(val) code and found
-> print(val)
(Pdb) p request.form
ImmutableMultiDict([('date1', ''), ('date2', ''), ('min1', ''), ('min2', ''),
('min3', ''), ('min4', ''), ('min5', ''), ('min6', ''), ('min7', ''), ('min8', ''),
('min9', ''), ('min10', ''), ('min11', ''), ('min12', ''), ('max1', ''), ('max2', ''),
('max3', ''), ('max4', ''), ('max5', ''),('max6', ''), ('max7', ''), ('max8', ''),
('max9', ''), ('max10', ''), ('max11', ''), ('max12', '')])
So we see checkboxSelectCombo is not part of the form. Right-clicking on the drop box and select Inspect, I examine the generated HTML and find
<input type="hidden" class="ui-igcombo-hidden-field" value="SAN FP Equity">
Ah, this element doesn't have a name. Your problem seems to be in your javascript, not flask.

How to select radio buttons and submit a form

This is the HTML:
<form method="post" action="./xxxxx" name="form1">
<input type="hidden" name="requestKey" value="52032a76cf53340b07052fd143feddc4a9d8f18130c80ec86003ab56e0d91b36"/>
<input type="hidden" name="option" value="txnlist">
<input type="hidden" name="account" value='1336169999'>
<input type="hidden" name="app" value="D">
<input type="hidden" name="lockType" value="">
<p><span class="header2"> Statement options </span>
<table summary="" width="100%" border="0" cellpadding="1" cellspacing="1">
<tr>
<td width="20"></td>
<td width="20"><input type="radio" name="optDateFilter" value="1"></td>
<td>Transactions for the last 30 days</td>
<td></td>
</tr>
<tr>
<td width="20"></td>
<td width="20"><input type="radio" name="optDateFilter" value="2"></td>
<td>Transactions for the last 90 days</td>
<td></td>
</tr>
<tr>
<td width="20"> </td>
<td width="20"><input type="radio" name="optDateFilter" checked='checked' value="3" style="vertical-align: middle"></td>
<td>
<div>
<font style="vertical-align: middle;">Transactions from </font>
<script src='jquery/js/ui/min/jquery.ui.datepicker.min-1.8.10.js'></script>
<script type='text/javascript'>$(function() {$('#datepicker1').datepicker( { changeMonth : true, changeYear : true, dateFormat : 'dd/mm/yy', showOn: 'both', buttonImage: 'images/calendar.png', buttonImageOnly: true }); }); </script>
<input type='text' id='datepicker1' name='txtFromDate' size='11' maxlength='10' value='14/12/2012' onchange="checkFromDate(document.form1.txtFromDate.value);document.form1.optDateFilter[2].checked = true;">
<font style="vertical-align: middle;">to</font>
<script type='text/javascript'>$(function() {$('#datepicker2').datepicker( { changeMonth : true, changeYear : true, dateFormat : 'dd/mm/yy', showOn: 'both', buttonImage: 'images/calendar.png', buttonImageOnly: true }); }); </script>
<input type='text' id='datepicker2' name='txtToDate' size='11' maxlength='10' value='01/01/2013' onchange="checkToDate(document.form1.txtFromDate.value,document.form1.txtToDate.value);document.form1.optDateFilter[2].checked = true;">
</div>
</td>
<td><font style="font-size: 8pt; vertical-align: middle;"><i>(maximum date range 3 months)</i></font></td>
</tr>
</table>
<table summary="" cellpadding="1" cellspacing="1" border="0">
<tr>
<td width="20"> </td>
<td width="20">
<a href="javascript:if(document.form1.optDateFilter[2].checked==true){CheckAndSubmit(document.form1.txtFromDate.value,document.form1.txtToDate.value);}else{showOverlay();document.form1.submit();};">
<img src="images/proceed.gif" alt="Show the selected range of transactions" border="0" width="22" height="22" />
</a>
</td>
<td>
Show the selected range of transactions
</td>
</tr>
</table>
</form>
This is the code i have, and it is not working:
self.browser.select_form('form1')
self.browser.form.set_all_readonly(False)
self.browser['txtFromDate'] = '28/12/12'
self.browser['txtToDate'] = '01/01/13'
resp = self.browser.submit()
html = resp.read()
I figured that i had to do this
self.browser.select_form('form1')
self.browser['optDateFilter'] = ['2']
self.browser.form.find_control(name="txtFromDate", id="datepicker1").value = "13/10/12"
self.browser.form.find_control(name="txtToDate", id="datepicker2").value = "01/01/13"
resp = self.browser.submit()
mechanize has a strange quirk: since there can be multiple radio button elements in a HTML document with the same name it insists that you use a list as value, even though only a single radio button may be selected at any time. That means that you need to use this:
self.browser.form.find_control(name='optDateFilter').value = ['2']
The same holds for checkboxes where it makes more sense because a user is allowed to select multiple values.

Categories