How to grab the value from the drop-down menu using flask - javascript

I am trying to grab the value from the drop-down menu after clicking the submit button for which the UI looks like this :
The code for the above is as follows :
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
app.debug = True
#app.route('/', methods=['GET'])
def dropdown():
colours = ['SBI', 'Kotak', 'Citi', 'AMEX', 'BOB', 'AXIS', 'HDFC', 'IDBI', 'YES', 'IndusInd']
return render_template('feba.html', colours=colours)
if __name__ == "__main__":
app.run()
index.html is in the templates folder
<!DOCTYPE html>
<html lang="en">
<style>
body {text-align:center}
</style>
<head>
<meta charset="UTF-8">
</head>
<body>
<img src="{{url_for('static', filename='logo_1.jpg')}}" align="middle" />
<h1>KARDFINDER</h1>
<h2>json file generator for banks</h2>
<select name="colour" method="GET" action="/">
<option value="{{colours[0]}}" selected>{{colours[0]}}</option>
{% for colour in colours[1:] %}
<option value="{{colour}}">{{colour}}</option>
{% endfor %}
</select>
<input type= "submit" name="submitbutton" value ="Submit"></body>
</html>
logo_1.jpg is in the static folder
My main aim to post this question is to get a solution with the help of which I can grab the value from the drop-down menu after the submit button is clicked and I want that value stored in a variable in the app.py file
Please Help me with this.

below code works on me,
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
app.debug = True
#app.route('/', methods=['GET'])
def dropdown():
colours = ['SBI', 'Kotak', 'Citi', 'AMEX', 'BOB', 'AXIS', 'HDFC', 'IDBI', 'YES', 'IndusInd']
return render_template('feba.html', colours=colours)
#app.route('/dropdown', methods = ['POST'])
def dropp():
dropdownval = request.form.get('colour')
print(dropdownval)
return redirect("/", code=302)
if __name__ == "__main__":
app.run()
<!DOCTYPE html>
<html lang="en">
<style>
body {text-align:center}
</style>
<head>
<meta charset="UTF-8">
</head>
<body>
<img src="{{url_for('static', filename='logo_1.jpg')}}" align="middle" />
<h1>KARDFINDER</h1>
<h2>json file generator for banks</h2>
<form method="POST" action="/dropdown">
<select name="colour">
<option value="{{colours[0]}}" selected>{{colours[0]}}</option>
{% for colour in colours[1:] %}
<option value="{{colour}}">{{colour}}</option>
{% endfor %}
</select>
<input type="submit" value ="Submit">
</form>
</body>
</html>
you should learn http requests, html forms and ajax

You could also just combine the index and drop down pages into one:
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
app.debug = True
#app.route('/', methods=['GET','POST'])
def dropdown():
colours = ['SBI', 'Kotak', 'Citi', 'AMEX', 'BOB', 'AXIS', 'HDFC', 'IDBI', 'YES', 'IndusInd']
if request.method=='POST':
var = request.form['var']
return render_template('feba.html', colours=colours)
if __name__ == "__main__":
app.run()
This is a bit simpler. You can use the same html code as Mert Celik but change action="/dropdown" to action="/"

Related

Is there any way to have my html page refresh/reload itself after a function in the django view.py tab completes?

I want to have my page refresh itself after a successful download of a zip file since successive attempts to click the submit button result in an error, and the only way to remedy it fairly easily is to manually refresh/reload the page. I was wondering if there is a way to set it up so that once the zip is completed the page will refresh itself without the user having to worry about it. Doing it this way also kills two birds with one stone, since I want to disable the submit button to prevent users from spamming it, but if I end up having the page refresh I could just out right remove it after it's clicked.
Here is my HTML code:
{% load static %}
<html>
<head>
<link rel="stylesheet" href="{% static '/styleSheet.css' %}">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edstore">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--BOOTSTRAP ASSETS-->
<link href="https://fonts.googleapis.com/css2?family=Quicksand:wght#400;700&display=swap" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %}
<div class="main_Body">
<div class="section">
<h1>Fileconverter</h1>
<br>
<label for="file_field" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i>Updload File(s)</label>
<input type="FILE" id="file_field" name="file_field" class="file-upload_button" multiple>
<label id="file_name"></label>
<br>
<br><br><br>
<br>
<button type="submit" class="file-submit__button" onclick="formDisableButton()" id="submitButton">Testing</button> <!--onclick="formDisableButton"-->
</div>
</form>
</body>
<footer>
<p>Click "Choose File(s)" and select the files you want to convert.</p>
<p>Once you click "Submit" the job will start.</p>
<p>Upon completion, a zip folder will be downloaded in your browser.</p>
<p>Do not click the submit buttons multiple times. If the tab is loading, the job is being processed.</p>
</footer>
</html>
<script>
document.querySelector("#file_field").onchange = function(){
document.querySelector("#file_name").textContent = this.files[0].name;
}
const tempButton = document.getElementById("submitButton");
function formDisableButton(){
// tempButton.disabled = true;
// setTimeout(formEnableButton, 10000);
location.reload();
}
function formEnableButton(){
tempButton.disabled = false;
}
/*setTimeout(()=>{
btn.disabled = false;
console.log('Button Activated')
}, 10000)*/
/* $(function(){
$("#submitButton").click(function(){
$("#submitButton").attr("disabled", "disabled");
setTimeout(function(){
$("#submitButton").removeAttr("disabled");
}, 10000)
});
});*/
</script>
And here is the views.py file:
from django.shortcuts import render
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic.edit import FormView
from django.views.decorators.csrf import csrf_exempt
from .forms import FileFieldForm
from django.http import HttpResponse
from .perform_conversion import FileConverter
import zipfile
import io
def FileFieldFormView(request, *args, **kwargs):
form = FileFieldForm(request.POST)
files = request.FILES.getlist('file_field')
if request.method == 'POST':
form = FileFieldForm(request.POST, request.FILES)
if form.is_valid():
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", False) as zip_file:
for f in files:
fileconverter = FileConverter(f.name)
fileconverter.run(f.file)
for img_name, img in fileconverter.output.items():
data = io.BytesIO(img)
zip_file.writestr(img_name, data.getvalue())
# Set the return value of the HttpResponse
response = HttpResponse(zip_buffer.getvalue(), content_type='application/octet-stream')
# Set the HTTP header for sending to browser
response['Content-Disposition'] = "attachment; filename=%s" % 'zip.zip'
response.set_signed_cookie('csrftoken', request.COOKIES['csrftoken'])
# Return the response value
return response
else:
return HttpResponse('Form Invalid')
else:
return render(request, 'pages/file_converter.html')
Based on what I've seen after doing digging before asking this question, Ajax seems to be the right direction for things, but I have no experience with it and everything I find online doesn't seem to apply to the type of question I'm asking. Also the onclick for the submit button doesn't work, but that's not a main problem right now. TBH any help would be massively appreciated!
Use javascript onclick to change the button class from class="file-submit__button" to something like class="file-submit__button-disabled", and of course add the corresponding css.

How can I get my html page to refresh upon completion of a django function?

I keep getting an error related to the csrf token when I try to employ consecutive submissions, and refreshing the page seems to work. The purpose of the program is to create zip files, so I figured the easiest solution would be to have the web page automatically reloaded once the zip file is done being created from the function in the views.py file and available for the user to open. The main issue I'm having is how to actually do that.
Here is the code for my HTML file:
{% load static %}
<html>
<head>
<link rel="stylesheet" href="{% static '/styleSheet.css' %}">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edstore">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--BOOTSTRAP ASSETS-->
<link href="https://fonts.googleapis.com/css2?family=Quicksand:wght#400;700&display=swap" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<form enctype="multipart/form-data" action="" method="post">
{% csrf_token %}
<div class="main_Body">
<div class="section">
<h1>Fileconverter</h1>
<br>
<label for="file_field" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i>Updload File(s)</label>
<input type="FILE" id="file_field" name="file_field" class="file-upload_button" multiple>
<label id="file_name"></label>
<br>
<br><br><br>
<br>
<input type="submit" class="file-submit__button" id="submitButton"> <!--onclick="formDisableButton"-->
</div>
</form>
</body>
<footer>
<p>Click "Choose File(s)" and select the files you want to convert.</p>
<p>Once you click "Submit" the job will start.</p>
<p>Upon completion, a zip folder will be downloaded in your browser.</p>
<p>Do not click the submit buttons multiple times. If the tab is loading, the job is being processed.</p>
</footer>
</html>
<script>
document.querySelector("#file_field").onchange = function(){
document.querySelector("#file_name").textContent = this.files[0].name;
}
const tempButton = document.getElementById("submitButton");
function formDisableButton(){
tempButton.disabled = true;
setTimeout(formEnableButton, 10000);
}
function formEnableButton(){
tempButton.disabled = false;
}
/*setTimeout(()=>{
btn.disabled = false;
console.log('Button Activated')
}, 10000)*/
/* $(function(){
$("#submitButton").click(function(){
$("#submitButton").attr("disabled", "disabled");
setTimeout(function(){
$("#submitButton").removeAttr("disabled");
}, 10000)
});
});*/
And this is the code from my views.py file:
from django.shortcuts import render
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic.edit import FormView
from django.views.decorators.csrf import csrf_exempt
from .forms import FileFieldForm
from django.http import HttpResponse
from .perform_conversion import FileConverter
import zipfile
import io
def FileFieldFormView(request, *args, **kwargs):
form = FileFieldForm(request.POST)
files = request.FILES.getlist('file_field')
if request.method == 'POST':
print(request)
form = FileFieldForm(request.POST, request.FILES)
if form.is_valid():
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", False) as zip_file:
for f in files:
fileconverter = FileConverter(f.name)
fileconverter.run(f.file)
for img_name, img in fileconverter.output.items():
data = io.BytesIO(img)
zip_file.writestr(img_name, data.getvalue())
# Set the return value of the HttpResponse
response = HttpResponse(zip_buffer.getvalue(), content_type='application/octet-stream')
# Set the HTTP header for sending to browser
response['Content-Disposition'] = "attachment; filename=%s" % 'zip.zip'
response.set_signed_cookie('csrftoken', request.COOKIES['csrftoken'])
# Return the response value
return response
else:
return HttpResponse('Form Invalid')
else:
return render(request, 'file_converter.html')
As a bonus if you're willing to provide a bit of extra help, I can't ever seem to have any sort of onclick for my submission button. Every time I try to add it, the python files never actually end up running and the page just sits there. I'd like to have it so that when the submission button is clicked it is removed form the page to prevent excessive submission attempts and since, in theory, the page will be refreshing after a successful run through, the submit button will just be reposted onto the page.

Add href in OnClick attribute in html form

I want to redirect to the python flask route home after showing the alert window.
<input type="submit" value="Register" onclick="call(); log();"></input>
Here are both functions.
<script>
function call()
{
window.alert("Congragulations! You Registerd Sucessfully ");
}
</script>
<script>
function log()
{
<a href="/home" > </a>
}
</script>
If I understood your project correctly, you want to forward the user after he has registered. At the same time, a message should appear that the process was successfully completed.
I think your javascript approach is not sufficient for this, since the data must first be sent from the client to the server so that the process is complete. Here the inputs should also be validated and will likely be processed or stored in some way.
I have written a small example for you, which accepts form data and checks it. If the verification is successful, the user is redirected and a message appears. To forward and display the message I use redirect and flash from the flask package.
Python Flask
import re
from flask import Flask
from flask import (
flash,
redirect,
render_template,
request,
session,
url_for
)
app = Flask(__name__)
app.secret_key = b'your secret here'
#app.route('/')
def home():
return render_template('index.html')
#app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form.get('username')
if username and re.match(r'^[a-z0-9\_\-]+$', username, re.IGNORECASE):
session['username'] = username
flash('Congragulations! You Registerd Sucessfully.')
return redirect(url_for('home'))
return render_template('register.html')
HTML (index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<nav>
<ul style="list-style: none;">
<li>Register</li>
</ul>
</nav>
{% with messages = get_flashed_messages() -%}
{% if messages -%}
<ul class="flashes">
{% for message in messages -%}
<li>{{ message }}</li>
{% endfor -%}
</ul>
{% endif -%}
{% endwith -%}
<h1>Welcome {{ session.get('username', 'Guest') }}!</h1>
</body>
</html>
HTML (register.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Register</title>
</head>
<body>
<form method="post">
<div>
<label for="username">Username</label>
<input type="text" name="username" id="username" />
</div>
<input type="submit" value="Register" />
</form>
</body>
</html>

Why can I not change a html element with JS?

I'm trying to get a JS script to insert HMTL on a python flask server and it doesn't seem to want to run.
File Structure:
project
static
css
style.css
templates
demo.html
download.html
index.html
wrongLink.html
main.py
Here is the flask code that runs the webserver:
from flask import Flask, render_template, send_file
from flask import request, redirect
app = Flask(__name__)
#app.route('/')
def main():
return render_template('demo.html')
I also render some templates like this:
return render_template('download.html',
thumb=thumb, title=title, options=options, counter=counter)
I realised that I'm having trouble specifically with one piece of JS in the download.html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link href="{{ url_for('static', filename='css/style.css') }}"
rel="stylesheet" type="text/css">
</head>
<body>
<div>
<form action="/getVideo" method="post">
<input type="text" name="Link" value="{{ Link }}">
<input type="submit" value="Convert">
</form>
<img src="{{ thumb }}" alt="Thumbnail" width="480" height="270">
<p>{{ title }}</P>
<p id="demo"></p>
<form id="options">
<input type="submit" value="Download">
</form>
</div>
<script type="text/javascript">
window.alert("JS works");
var i;
var options = JSON.parse{{options | tojson}};
for (i = 0; i < options.length; i++) {
out += '<input type="radio" value="' + options[i]["res"] += '"><br>';
}
document.getElementById("demo").innerHTML = "hi";
</script>
</body>
</html>
Neither the alert window or the element edit execute so I'm not sure what's happening there.

How to hyperlink to html

Please help, I have provided below three files: application.py, ask.html, and link.html. In ask.html, I'm trying to ask the user to provide me a link. They will then be redirected to link.html where there is a button to take them to that link. But once the button is pressed, it doesn't take me to the link, comes out error 404 not found.
In application.py:
#app.route("/")
def ask():
return render_template("ask.html")
#app.route("/link")
def link():
weblink = request.args.get("weblink")
return render_template("link.html", weblink=weblink)
In ask.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ask</title>
</head>
<body>
<form action="/link">
<input placeholder="weblink here" name="weblink" type="text">
<input type="submit">
</form>
</body>
</html>
In link.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ask</title>
</head>
<body>
Go to Link
</body>
</html>
First, change:
<form action="/link">
to:
<form action="/link" method="post">
Then, in link():
#app.route("/link", methods = [“GET”, “POST”])
def link():
weblink = request.form.get("weblink")
...
Change
<form action="/link">
To
<form action = "{{url_for('link')}}" method = "post">
in application.py
change
#app.route('/link')
to
#app.route('/link', methods=['GET', 'POST'])
def link():
if request.method == 'POST':
weblink = request.form.get('weblink')
return render_template('link.html', weblink=weblink)

Categories

Resources