I am trying to pass an index back to python from the user on click in a Flask template. I am already getting information from the same route I'm trying to pass the index to, but I have not figured out how to POST to it. I have put the index value inside the <button>, which is inside the <form>.
Here's my template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello world!</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('a#test').bind('click', function() {
$.getJSON('/download_file',
function(data) {
//do nothing
});
return false;
});
});
</script>
<div>
<h1>messages list</h1>
<div>
<ol>
{%for index, message in enumerate(messages)%}
<li>{{ index }}{{ message.date }}-{{message.name}}</li>
<form method="POST">
<input type="hidden" value="{{index}}" name="index" />
<a href="" id=test><button value="index" class='btn btn-default'>Download</button></a>
</form>
{%endfor%}
</ol>
</div>
</div>
</body>
</html>
and my '/download_file' route
#app.route('/download_file', methods=['POST'])
def save_doc():
index = request.form.get('index')
filepath = os.path.join(os.path.expanduser('~') + r'\Desktop', filename)
messages_list[0].document.save(filepath)
return 'yo'
There's nothing on your form that actually submits the value of index. This is assuming you want to do a standard form submit (instead of ajax):
You may want to add something like <input type="hidden" value="{{index}}" name="index" /> to your form, along with index = request.form.get('index') in your route.
Related
This is my HTML code:
<!DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static 'jquery-3.6.2.min.js' %}" ></script>
<script src="{% static 'jquery.js' %}" ></script>
</head>
<body>
<form action="{% url 'index' %}" method="post">
{% csrf_token %}
<button name="button1">button1</button>
<button name="button2">button2</button>
<input type="text" name="textbox">
</form>
</body>
</html>
Every time I type some text in the textbox, let's say I type: "hi" and hit enter, the request.POST returns:
<QueryDict: {'csrfmiddlewaretoken': ['FX1qFNzbQUX3fYzAwW27cOu83omLzifnlLU5X0WXXVdOiyNretM5b3VgsGy1OogA'], 'button1': [''], 'textbox': ['hi']}>
Why does request.POST contain 'button1': [''] even though I haven't clicked on it?
Is there a way to avoid request.POST to have 'button1': ['']?
Remove a name attribute from your <button> tag if you don't need to know which buttons is pressed by a user:
<form action="{% url 'index' %}" method="post">
{% csrf_token %}
<button>button1</button>
<button>button2</button>
</form>
As the button is an input as well and can contain name and value.
Alternatively you may use the feature to implement the following approach if you wish to vary your backend logic dependant of which button is pressed:
In a template file:
<form action="{% url 'index' %}" method="post">
{% csrf_token %}
<button name="action" value="button1_pressed">button1</button>
<button name="action" value="button2_pressed">button2</button>
</form>
In your views.py:
if request.method == "POST":
back = reverse('index')
action = request.POST.get("action")
if action == "button1_pressed":
# do something
messages.success(request, "Successed!")
return redirect(back)
if action == "button2_pressed":
# do something else
messages.success(request, "Successed!")
return redirect(back)
you may Try
<!--base.html-->
{% load static %}
<!DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="{% static 'jquery-3.6.2.min.js' %}" ></script>
<script src="{% static 'jquery.js' %}" ></script>
</head>
<body>
{% block content %}
<form action="{% url 'index' %}" method="post">
{% csrf_token %}
<input type="text" name="textbox">
<button name="button1">button1</button>
<button name="button2">button2</button>
</form>
{% endblock %}
</body>
</html>
I am trying to pass in a list of classes into a checkbox (this works), and when the Submit button is clicked, I want to make a Post Request to send all the selected boxes to the backend and then also go to the next page (Does not work).
Here is my HTML page right:
<!doctype html>
<html lang="en">
<head>
<style>
h1 {color: rgb(240, 112, 38);}
</style>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
function myFunction() {
window.location.href="./classinfo";
}
function sendPOST() {
let formData = { user_classes: $("#user_classes").val() };
$.post("/class", formData)
};
</script>
</head>
<body style="background-color:powderblue;">
<div class="container">
<br>
<h1>What Classes Have You Taken</h1>
<div class="form-group row">
<label class="col-lg-12">
<form method="POST" action='/class'>
<label class="col-xs-6" style="font-family:verdana;">
{% for c in cs_req %}
<input type="checkbox" style="text-align:left;" name = 'user_classes' option value = "{{c}}" SELECTED> {{c}}<br></option>
{% endfor %}
</label>
<br>
<input class="btn btn-secondary" style="font-family:verdana;" type="Submit" onclick="sendPOST();MyFunction()">
</form>
</label>
</div>
<div id="content">
</div>
</div>
<script>
$(document).ready(function(){
$('.selectpicker').selectpicker();
})
</script>
</body>
</html>
and my backend function is this:
#app.route('/class', methods=["POST"])
def store_classes():
"'Based on checkboxes selected from checkboxes(), store the classes in txt'"
user_classes = request.form.getlist('class') #--> returns nothing
return render_template("class.html")
My onclick is not sending the post request or going to the next page. I'm not sure how to solve this so any advice is appreciated.
I have some function, which can be running for a continuous period of time, I run it using FastAPI background tast like that:
background_tasks.add_task(my_func)
after that returning template with progressbar using
return templates.TemplateResponse('progressbar.html', context={"request": request})
How can I define the length of a progressbar iteration and send values to show progress?
progressbar.html:
<html>
<head>
<title>Upload data</title>
<link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
<link href="{{ url_for('static', path='/progressbar.css') }}" rel="progressbar">
</head>
<body>
<a>Uploading</a>
<div>
<progress id="progressbar"></progress>
</div>
<form action="/final" method="get" >
<h1>
<input type="submit" value="Start upload">
</h1>
</a>
</form>
<p>Return to home page home page</p>
</body>
</html>
I am creating a project on examination.
In my first html page I have a set of hyperlinks which represent the name of question papers. The question papers are stored in the form of tables in MySQL.
What I want is,to return the name of the hyperlink clicked by the user in my python code.
All the links should lead to the same webpage,but the contents in each link is different.
This is my python code for the webpage which should open after one of the links is clicked:
#app.route('/qsetdisplay/exam',methods=['GET','POST'])
def exam():
if request.method == 'POST':
if 'answer' in request.form:
cursor5 = db3.cursor(pymysql.cursors.DictCursor)
tablename = request.args.get('type')
print(tablename)
cursor5.execute("select questions from {}".format(tablename))
cursor5.execute("select answers from {}".format(tablename))
cursor5.execute("select marks from {}".format(tablename))
print("ques:", ques)
print("ans:", ans)
print("marks:",marks)
return render_template('exam.html',ques=ques,marks=marks,ans=ans)
tablename returns as none in the above code.
This is my html code for the webpage which would open after oneof the links is clicked:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>EXAMINATION</title>
</head>
<body>
<div>
<form name="ex" id="ex" action="{{url_for('exam')}}" method=POST>
<h1 align="centre">ALL THE BEST!!!</h1>
{% for que in ques %}
<h6>{{que}}</h6>
<textarea name="answer" id="answer" placeholder="enter answer" rows="10" cols="100"></textarea><br><br>
{% endfor %}
<input name="sub" id="sub" type="submit" value="submit">
</form>
</div>
</body>
</html>
And this is the html code for the previous page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>STUDENT PROFILE</title>
</head>
<body>
<div>
<form action="/">
<h1>"WELCOME STUDENT"</h1>
</form>
</div>
<div>
<form name="QD" action="{{url_for('qset_display')}}" method="get">
<input name="QD" value="CLICK TO VIEW QUES PAPERS" type="submit"><br><br><br><br>
<h1>THESE ARE THE AVAILABLE PAPERS:</h1>
{% for name in names %}
{{name}}<br><br>
{% endfor %}
</form>
</div>
</body>
</html>
How can I correct my code?
I am trying to build a blog using flask. SimpleMDE is used as post editor(html code below). I want to save the markdown content to local file and render by flask-misaka in jinja2.
In SimpleMDE, I can get raw markdown content by simplemde.value(). But when I pass simplemde.value() to var in javascript. "\n" is missing aftering passing. I think it may have some "magic" tools in javascript. The html code return 2 alert message, first message contains line feed, the second doesn't.
Could somebody give me some hits about this problems?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Editor</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel='stylesheet' href='.{{ url_for("static", filename="css/simplemde.min.css") }}'>
<script src='.{{ url_for("static", filename="js/simplemde.min.js") }}'></script>
</head>
<script type='text/javascript'>
function check() {
var raw = simplemde.value();
alert(raw);
document.testform.markdown_raw.value=raw;
alert(document.testform.markdown_raw.value);
}
</script>
<body>
<form method='post' class='form' role='form' name='testform'>
<div class="form-group " style="padding-top:10px">
<input class="form-control" id="post_title" name="post_title" type="text" value="Title?">
</div>
<div class="form-group">
<input class="form-control" id="markdown" name="post_content" type="textarea" value="">
</div>
<div class="form-group" style='display:none'>
<input class="form-control" id="markdown_raw" name="markdown_raw" type="textarea" value="Origin">
</div>
<div>
<input class='btn btn-default' onclick="check();" id='submit' name='submit' type='submit' value='Save'>
<input class='btn btn-default' id='publish' name='publish' type='submit' value='Publish'>
</div>
</form>
<script type='text/javascript'>
var simplemde = new SimpleMDE({ element: document.getElementById('markdown') });
</script>
</body>
</html>
If you want to get raw markdown, just use simplemde.value().
When you put raw markdown into normal textarea, it turns into pure text.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Editor</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
<script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
</head>
<body>
<form method='post' class='form' role='form' name='testform'>
<div class="form-group " style="padding-top:10px">
<input class="form-control" id="post_title" name="post_title" type="text" value="Title?">
</div>
<div class="form-group">
<textarea class="form-control" id="markdown" name="post_content"></textarea>
</div>
<div>
<input class='btn btn-default' onclick="" id='submit' name='submit' type='submit' value='Save'>
<input class='btn btn-default' id='publish' name='publish' type='submit' value='Publish'>
</div>
</form>
<script type='text/javascript'>
var simplemde = new SimpleMDE({ element: document.getElementById('markdown') });
</script>
</body>
</html>
Get the content:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def test():
if request.method == 'POST':
raw_md = request.form['post_content']
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)