How to load content into div element with flask - python

I'd like to fill / update a div area in index.html with the result from the python function, but I don't know how to do this. I know there are several other questions with a similar topic but I couldn't succeed with them because they were too specific. I'm pulling my hair out over this.
Would be someone so nice and guide me?
This is a function in main.py:
#app.route('/')
def index():
return render_template('index.html')
#app.route('/stat/')
def stat():
a = 2
b = 10
return(str(a) + ' is not ' + str(b))
this is the index.html:
<body>
<form action="/stat/">
<button type="submit" id="btn1" class="btn btn-primary btn-sm">check stat</button>
</form>
<div id="stat_content"></div>
</body>

As #S3DEV points out, you will need to pass the string to the template via an additional argument. For example, we might do something like this:
#app.route('/stat/', methods=['GET', 'POST']) # EDIT
def stat():
a = 2
b = 10
text = f"{a} is not equal to {b}"
return render_template("index.html", text=text)
In the code above, we set text to be the string to be passed to the template. In the template, we will be able to access this string variable as text.
Now when index.html is rendered, it will be looking for the text variable that is passed in from the Flask application. This is taken care of by Jinja 2, which is the rendering engine used by Flask.
<div id="stat_content">
{% if text %}
<h2>No text to show</h2>
{% else %}
<h2>{{ text }}</h2>
{% endif %}
</div>
Using Jinja 2 syntax with curly braces, we first check if the text variable exists or not; if it does not exist, we render the message, "No text to show." This will happen when we first route into "/", or the default home route of the Flask app.
Once the user fills out the form, however, they will be redirected to "/stat/", at which point we will now have generated text and passed it back to index.html via the render_template("index.html", text=text) function call. Then, when Jinja 2 renders index.html, it will see that text was passed over from the Flask app and display that message, namely that 2 is not equal to 10.

You want this initiated from the button right? Here's how to achieve that with ajax...
<body>
<form action="/stat/">
<button type="submit" onclick="GetData();" id="btn1" class="btn btn-primary btn-sm">check stat</button>
</form>
<div id="stat_content"></div>
</body>
<script type="text/javascript">
function GetData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
if (xmlhttp.status == 200) {
document.getElementById("stat_content").innerHTML = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "/stat/", true);
xmlhttp.send();
}
</script>

to update the content of that div, i think (based on your logic) you need to perform an ajax call to your stat function with the two parameters a and b submitted via POST request:
<form class="form-stat needs-validation" novalidate role="form">
<div class="form-group">
<input type="text" class="form-control" name="a" value="">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="b" value="">
<div class="invalid-feedback"></div>
</div>
<button type="submit" id="btn1" class="btn btn-primary btn-sm">check stat</button>
</form>
<div id="stat_content">Output: ?</div>
put the javascript code below after jquery call
<script>
$(document).ready(function() {
"use strict";
$('.form-stat').submit(function(e) {
e.preventDefault();
$.ajax({
url: "{{ url_for('stat') }}",
type: 'POST',
cache: false,
dataType: 'json',
data: $('.form-stat').serialize(),
success: function(data) {
// console.log(data);
$('.form-stat input[name=a]').val(''); // reset field
$('.form-stat input[name=b]').val(''); // reset field
$('#stat_content').html(data); // update div with the returned vlue
}
});
});
});
</script>
and you have to make little change to your stat function so you can submit dynamically the two parameters via POST like so :
from flask import Flask, request, make_response
import json
#app.route('/stat', methods=['POST'])
def stat():
if request.method == 'POST':
a = request.form['a']
b = request.form['b']
# check if inputs are valid to work with ..
res = str(a) + ' is not ' + str(b) if a != b else str(a) + ' and ' + str(b) + ' are equal.'
resp = make_response(json.dumps(res))
resp.status_code = 200
return resp

Related

Read from two different forms in Flask

In my page I have two different forms. I want to read the information from the first form whenever I press a button in the second form. Is this possible?
First form:
<form id="loadData" method="post" action="/loadData">
{% if day %}
Day: <input id="day" name="day" size="5px" value={{day}}>
Month: <input id="month" name="month" size="5px" value={{month}}>
Year: <input id="year" name="year" size="5px" value={{year}}>
{% else %}
Day: <input id="day" name="day" size="5px">
Month: <input id="month" name="month" size="5px">
Year: <input id="year" name="year" size="5px">
{% endif %}
.
.
.
</form>
Second form:
<form id="createFile" method="post" action="/createFile">
<button type="submit">Create</button>
</form>
By clicking the button in the second form I want to read the information in the first one to create a file containing all those information.
I tried something like
#app.route("/createFile", methods=["GET", "POST"])
def createFile():
if request.method == "POST":
day = request.form["day"]
month = request.form["month"]
year = request.form["year"]
return redirect('/')
but I can't manage to read those variable properly.
Despite corresponding in the comments i'm not entirely sure this is your end goal, but let's give it a go?
basically all i did was copy stuff from the links attached in the comment.
a.html:
<form id="form_id" action="/loadData" method="POST">
<input type="text" name="q" value="abcd">
<button type="submit">loadData</button>
</form>
<button id="createFile"> createFile </button>
<script>
function post(path, params, method = 'post') {
// The rest of this code assumes you are not using a library.
// It can be made less verbose if you use one.
const form = document.createElement('form');
form.method = method;
form.action = path;
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = params[key];
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
var form_1 = document.querySelector('#form_id')
document.querySelector('#createFile').addEventListener('click', (e) => {
var data = Object.fromEntries(new FormData(form_1).entries());
post("/createFile",data)
});
</script>
app.py:
from crypt import methods
from flask import Flask, request
app = Flask(__name__)
#app.route("/loadData", methods=["POST"])
def loadData():
data = request.get_data()
return f"<h1 style='color:blue'>loadData data: {data}</h1>"
#app.route("/createFile", methods=["POST"])
def createFile():
data = request.get_data()
return f"<h1 style='color:red'>createFile data: {data}</h1>"
if __name__ == "__main__":
app.run(host='0.0.0.0')
page looks like this:
clicking on loadData:
clicking on createFile:
this whole setup is pretty convoluted and unnecessarily complex. what are you trying to achieve?

How can I CSS-style different returns from the same Python function?

I have a Python function which returns different messages in different scenarios. I want to style different messages differently, but I don't know how to do it.
This is my function:
def checkans(request, spanish_id):
random_spanish_question = get_object_or_404(Spanish, pk=spanish_id)
query = request.GET.get('ans')
coreng = random_spanish_question.english_set.get()
if query == str(coreng):
message = {
'message' : "Correct!"
}
return JsonResponse(message)
else:
message = {
'message' : "Incorrect. The correct answer is " + str(coreng)
}
return JsonResponse(message)
This is the HTML page:
<div class="flexcontainer" style="justify-content: center;">
<div class="sectiontitle">Quiz time
</div>
<div class="question_card">
<div class="question_word">{{ random_spanish_question }}</div>
<div id="msg"></div>
<form action="/checkans/{{random_spanish_question.id}}/" method="get">{% csrf_token %}
<label for="ans">Answer:</label>
<input type="text" name="ans"autofocus autocomplete="off" id="ansfield"/>
<input type="submit" value="Submit"/ id="submitbtn">
</form>
<input type="submit" value="Skip"/>
<button onclick="location.reload();">Next</button>
</div>
</div>
And this is the JS and AJAX code:
$('form').on('submit', function(e){
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: 'GET',
url: url,
data: form.serialize(),
success: function(data){
$("#msg").html(data.message);
}
});
disable();
})
function disable(e){
$('#submitbtn').prop('disabled', true);
$('#ansfield').prop('disabled', true)
}
For example, I want to make the "Correct!" message green, while if it returns "Incorrect...", I want it to be red, and underline the answer, "str(coreng)". Please tell me how I can do it. Thanks in advance!
def checkans(request, spanish_id):
random_spanish_question = get_object_or_404(Spanish, pk=spanish_id)
query = request.GET.get('ans')
coreng = random_spanish_question.english_set.get()
if query == str(coreng):
message = {
'message' : "<span class=\"result-correct\">Correct!</span>"
}
return JsonResponse(message)
else:
message = { =
'message' : "<span class=\"result-incorrect\">Incorrect. The correct answer is " + str(coreng)</span>
}
return JsonResponse(message)
where those classes are defined in css:
.result-correct{
color:#00aa00; // or any shade of green you like
}
.result-incorrect{
color:#aa0000; // or any shade of red you like
}

How to display mySQL data from server side to HTML from AJAX

I can't find many tutorials on this, mostly could find ones for PHP. I am trying to create a search bar with an autocomplete feature using python Flask, mySQL, and Ajax. I got things working up to capturing the keystroke and selecting from the database. After that, I can't get any of this to display on the client side.
I've tried using a partial page but none of this will display.
server.py file
#app.route("/search", methods=['POST'])
def search():
output = ''
mysql = connectToMySQL("countries_db")
data_received = json.loads(request.data)
data = data_received['query']
var_data = '%' + data + '%'
mysqlQuery = "SELECT name FROM countries WHERE countries.name LIKE '%s' LIMIT 10;" %var_data
result = mysql.query_db(mysqlQuery)
output += '<ul class="list-unstyled">'
if len(result) > 0:
for country in result:
output += '<li>' + country["name"] + '</li>'
else:
output += '<li>Country Not Found</li>'
output += '</ul>'
return render_template("index.html", result=result)
index.html
<li class="search">
<div class="auto">
<img src="{{ url_for('static', filename='search.png') }}">
<input class="search-bar" type="text" id="country" name="country" aria-label="Search through site content"
placeholder="Search for a Country">
<div class="countryList">
{% for country in result %}
<p>{{country.name}}</p>
{% endfor %}
</div>
</div>
</li>
# Ajax
<script type="text/javascript">
$(document).ready(function () {
$('#country').keyup(function () {
var query = $(this).val();
if (query != '') {
$.ajax({
url: "/search",
method: "POST",
data: JSON.stringify({
query: query,
}),
dataType: "JSON",
contentType: 'application/json;charset=UTF-8',
success: function (data) {
data = data.data
$('#countryList').fadeIn();
$('#countryList').html(data)
},
dataType: 'text'
})
}
})
})
ids are refferred using # and class names are referred using . in Jquery. Replace the # before country-list with '.'

django passing arguments from template to bash script

I am trying to have an input field in the template that the user enters a query and that query goes to the views.py
and from there i m taking the query and pass it as argument to the bash script.
This is what i have for now.
views.py
def home(request):
if request.method == 'POST':
try:
query = request.POST['query']
test = subprocess.check_call(['home/.../bash.sh',
query])
return render(request, 'base.html', {'input': test})
except KeyError:
return HttpResponse("Nothing was submitted!")
base.html
<form action="/" method="post">
{% csrf_token %}
<input type="hidden" name="query" value="{{ input }}">
<input type="submit" value="Submit">
</form>
I am stuck right here..i don't know if i shout request.POST or something else much simpler...cause i don't want to use a form.
I figure it out by creating a script in the html template.
<script>
$(".opener").click(function () {
var thead = $("#mytable").find("thead");
thead.find('th').last().remove();
thead = thead.html();
var row = $(this).parents('tr');
row.find('td').last().remove();
row = row.html();
var table = $(document.createElement('table'));
table.append('<thead>' + thead + '</thead>');
table.append('<tbody><tr>' + row + '</tr></tbody>')
$(".modal").html("").append(table);
$(".modal").dialog({width: 'auto', position: 'top'});
});
</script>

Django basic form - read a variable from views.py

I'm trying to implement a form of a single field in Django. The objective is to pass an integer variable (counter) to the views.py file. The template is completely custom, the value of the variable "counter" is shown in the screen while it can be increased/decreased using two buttons.
I can't manage to read this variable from my views.py file, and I have no idea what I am doing wrong. This is what I've done:
Template file:
<form method="POST" action="{% url 'animo' ejercicio=ejercicio %}">{% csrf_token %}
<p class="mensaje">{{pregunta_valoracion}}</p>
<div id="contadormin">
<input type="button" id="number-change-button" value="-" onclick="subtract()" name="counter"/>
<div id="minutos">
<p id="counter">0 {{unidad}}</p>
</div><script>
var i = 0;
var uni = {{unidad}};
function add() {
document.getElementById('counter').value = ++i;
document.getElementById('counter').innerHTML = i;
}
function subtract() {
if (i> 0){
document.getElementById('counter').value = --i;
document.getElementById('counter').innerHTML = i;
}
}
</script>
<input type="button" id="number-change-button" value="+" onclick="add()" name="counter" />
</div>
<input type="submit" class="save btn btn-default" value= "HECHO"</input>
</form>
Views file:
if request.method == 'POST':
veces = request.POST.get('counter', '')
Any ideas?
The only items with name="counter" in your template are the + and - buttons. You don't actually have a field containing the counter value itself, so there's no way it can be submitted in the form.
Remove the "counter" names from those buttons, and instead of putting the counter value in a <p> element, put it in an <input name="counter">.

Categories