Passing a session variable between Templates in Flask - python

I'm trying to assign a session variable in one Template and pass it to another, but I keep getting KeyError: 'var' error. I'm not sure what I'm doing wrong here. My views.py looks as follows:
from flask import Flask, request, jsonify, session
from app import app
#app.route('/activity', methods=['GET', 'POST'])
def activity():
user = session['var']
location = {'mspace': 'Central Library'}
return render_template('activity.html',
location = location,
user = user)
#app.route('/', methods=['GET', 'POST'])
#app.route('/index', methods=['GET', 'POST'])
def index():
global checkCheck
print "starting"
if request.method == 'POST':
# print(request.data)
checkCheck = True
location = {'mspace': 'Central Library'}
user = {'nickname': request.args.get('name')}
session['var'] = user
# print user['nickname']
print session['var']
return render_template('index.html',
location = location,
user = user)
return render_template('index.html',
location = "test",
user = 'user')
and here's my activity.html:
<html>
<head>
<title>{{ location['mspace'] }} - Makerspace </title>
</head>
<body>
<h1>Hello, {{ user['nickname'] }} - what activity are you doing today:</h1>
<form action="" method="">
<h3> Choose your Activity</h3>
<select name="activity">
<option value='3dprinting'>3D Printing</option>
<option value='Minecraft'>Minecraft</option>
<option value='Arduino'>Arduino</option>
<option value='Wearables'>Wearables</option>
</select>
</body>
</html>
Here's my index.html:
<html>
<head>
<title>{{ location['mspace'] }} - Makerspace </title>
</head>
<body>
<h1>Hello, {{ user['nickname'] }}!</h1>
</body>
<script>
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send(null);
return xmlHttp.responseText;
}
setInterval(checkFunc(), 1000);
function checkFunc(){
var json = httpGet("/getSignIn");
console.log("yes!");
obj = JSON.parse(json);
console.log(obj.newCheckin);
if(obj.newCheckin){
window.location.replace("http://127.0.0.1:5000/activity");
}
else{
setInterval(checkFunc(), 1000);
}
}
</script>
</html>

Related

405: Method Not Allowed. Why am I getting this error in Flask

I tried all posiible ways and read many posts in SO. I haven't got any solution for my "method not allowed" error. Can anyone check and let me know what did I do wrong? I am getting frustrated cause I am new to flask and I cannot proceed further.
This is my template file add_cars.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Datastore and Firebase Auth Example</title>
<script src="https://www.gstatic.com/firebasejs/ui/4.4.0/firebase-ui-auth.js"></script>
<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.4.0/firebase-ui-auth.css" />
<script src="{{ url_for('static', filename='script.js') }}"></script>
<link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='navstyle.css') }}">
</head>
<body>
<div class="topnav">
<a class="active" href="{{ url_for('root') }}">Home</a>
EV List
Contact
About
</div>
<h2>Add car details</h2>
<div id="firebase-auth-container"></div>
{% if user_data %}
<p align="right">Email: {{ user_data['email'] }}</p>
<button id="sign-out" hidden="true" style="float: right;">Sign out</button>
<div id="login-info" hidden="true">
<form action="/add_cars" method="post">
Car name:<input type="text" value="" name="name_update"/><br/>
Manufacturer:<input type="text" value="" name="manufacturer_update"/><br/>
Year:<input type="number" value="" name="year_update"/><br/>
Battery size:<input type="number" value="0.0" name="battery_update" step="any"/><br/>
Range:<input type="number" value="" name="range_update"/><br/>
Cost:<input type="number" value="" name="cost_update"/><br/>
Power:<input type="number" value="" name="power_update" step="any"/><br/><br>
<input type="submit" class="button-1" value="Add details" name="submit_button"/>
</form>
{% elif error_message %}
<p>Error Message: {{ error_message }}</p>
{% endif %}
</div>
<br>
<!-- <div>-->
<!-- View all cars-->
<!-- </div>-->
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.0/firebase-auth.js"></script>
<script src="{{ url_for('static', filename='app-setup.js') }}"></script>
</body>
</html>
This is my main.py
from flask import Flask, render_template, request, redirect, url_for
import google.oauth2.id_token
from google.auth.transport import requests
from google.cloud import datastore
import os, random
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="google_auth_json.json"
firebase_req_adapter=requests.Request()
app = Flask(__name__)
datastore_client = datastore.Client()
def store_time(email):
entity = datastore.Entity(key = datastore_client.key('User', email, 'visit'))
entity.update({'email' : email})
datastore_client.put(entity)
def retrieveCarInfo(claims):
entity_key = datastore_client.key('CarInfo', claims['email'])
entity = datastore_client.get(entity_key)
return entity
def createCarInfo(claims):
entity_key = datastore_client.key('CarInfo', claims['email'])
entity = datastore.Entity(key = entity_key)
entity.update({
'email': claims['email'],
'name': claims['name'],
'cars_list': []
})
datastore_client.put(entity)
def retrieveCars(car_info):
car_ids = car_info['cars_list']
car_keys = []
for i in range(len(car_ids)):
car_keys.append(datastore_client.key('car', car_ids[i]))
cars_list = datastore_client.get_multi(car_keys)
return cars_list
def createCarDetails(claims, new_car_string, new_man_string, new_yr_int, new_bt_float, new_rg_int, new_cost_int, new_pr_int):
id = random.getrandbits(63)
entity_key = datastore_client.key('car', id)
entity = datastore.Entity(key = entity_key)
entity.update({
'name': new_car_string,
'manufacturer': new_man_string,
'year': new_yr_int,
'battery_size': new_bt_float,
'range': new_rg_int,
'cost': new_cost_int,
'power': new_pr_int,
})
datastore_client.put(entity)
return id
def addcarToUser(car_info, id):
car_keys = car_info['cars_list']
car_keys.append(id)
car_info.update({
'cars_list': car_keys
})
datastore_client.put(car_info)
def deleteCars(claims, id):
car_info = retrieveCarInfo(claims)
car_list_keys = car_info['cars_list']
car_key = datastore_client.key('Car', car_list_keys[id])
datastore_client.delete(car_key)
del car_list_keys[id]
car_info.update({
'car_info' : car_list_keys
})
datastore_client.put(car_info)
# All functions below to render data to templates
#app.route("/")
def root():
id_token = request.cookies.get("token")
error_message = None
claims = None
car_info = None
cars = None
if id_token:
try:
claims = google.oauth2.id_token.verify_firebase_token(id_token,
firebase_req_adapter)
store_time(claims['email'])
car_info = retrieveCarInfo(claims)
if car_info == None:
createCarInfo(claims)
car_info = retrieveCarInfo(claims)
cars = retrieveCars(car_info)
except ValueError as exc:
error_message = str(exc)
return render_template('index.html', user_data=claims, error_message=error_message,
car_info=car_info, cars=cars)
# return render_template('index.html', user_data=claims, error_message=error_message)
#app.route("/add_cars", methods=['POST'])
def add_ev():
# add ev's
id_token = request.cookies.get("token")
error_message = None
claims = None
car_info = None
if id_token and request.method=='POST':
try:
claims = google.oauth2.id_token.verify_firebase_token(id_token, firebase_req_adapter)
car_info = retrieveCarInfo(claims)
id = createCarDetails(claims,
request.form['name_update'],
request.form['manufacturer_update'],
request.form['year_update'],
request.form['battery_update'],
request.form['range_update'],
request.form['cost_update'],
request.form['power_update'])
addcarToUser(car_info, id)
except ValueError as exc:
error_message = str(exc)
return redirect(url_for("add_ev"))
# return render_template('add-cars.html', user_data=claims, error_message=error_message, car_info=car_info)
#app.route("/list")
def list_ev():
# listing all ev's
id_token = request.cookies.get("token")
error_message = None
claims = None
car_info = None
if id_token:
try:
claims = google.oauth2.id_token.verify_firebase_token(id_token,
firebase_req_adapter)
car_info = retrieveCarInfo(claims)
if car_info == None:
createCarInfo(claims)
car_info = retrieveCarInfo(claims)
except ValueError as exc:
error_message = str(exc)
return render_template('list_ev.html', user_data=claims, error_message=error_message, car_info=car_info)
#app.route('/delete_cars/<int:id>', methods=['POST'])
def deleteCarFromUser(id):
id_token = request.cookies.get("token")
error_message = None
if id_token:
try:
claims = google.oauth2.id_token.verify_firebase_token(id_token, firebase_req_adapter)
deleteCars(claims, id)
except ValueError as exc:
error_message = str(exc)
return redirect('/')
if __name__=='__main__':
app.run(host='127.0.0.1', port=8082, debug=True)
Update:
When you redirect you will eventually send a GET request to your endpoint, however your endpoint only supports POST.
Therefore you should make a different endpoint then, which supports GET and hosts the template you referenced above. Then the form of the template can send a POST to the add_ev endpoint, and then the add_ev redirects to the new GET endpoint and the loop is closed.
Previous suggestion:
Could you try adding GET as a supported method to the below endpoint?
#app.route("/add_cars", methods=['GET', 'POST'])
def add_ev():
# add ev's
...
You need to add support for GET inside your add_ev and limit redirect to POST only (otherwise you will end with endless loop) i.e. something akin to
#app.route("/add_cars", methods=['GET','POST'])
def add_ev():
...
if request.method == 'POST':
return redirect(url_for("add_ev"))
elif request.method == 'GET':
return render_template('add_cars.html')

Flask go to new page on button click

I have a small flask app with an index page where the user selects a directory from a drop down menu. Once the user makes a selection and clicks "submit" on the webpage I would like to send them to a new page with info specific to that directory.
I'm trying to load the new page by simply calling the function after getting the input from the index page. My issue is that clicking submit on the webpage reloads the same index page.
Flask Code:
app = Flask(__name__)
dirname = os.path.dirname(sys.argv[0])
run_path = ""
#app.route("/", methods = ["GET", "POST"])
def index():
dir_loc = "/Users/kregan1/Documents"
dir_data = list(os.listdir(dir_loc))
if request.method == "POST":
run_dir = request.form.get("run_list")
run_path = dir_loc + "/" + run_dir
run(run_path)
return render_template('index.html', data = dir_data)
#app.route("/run", methods = ["GET", "POST"])
def run(run_path):
if os.path.isdir(run_path) == True:
file_lists = []
for f in os.listdir(run_path):
if f.startswith("pattern"):
file_lists.append(run_path + "/" + f)
projects = []
for fl in file_lists:
with open(fl) as f:
for row in f:
if row.split(",")[0] not in projects:
projects.append(row.split(",")[0])
else:
projects = ["a","b","c"]
return render_template('run.html', run = run_path, proj_data = projects )
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="{{url_for('static', filename='asp_javascript.js')}}"></script>
</head>
<body>
<h2>Packaging Tool - Index</h2>
<p>Select Run:</p>
<form action="{{ url_for("index") }}" method="post">
<select name="run_list">
{% for d in data %}
<option>{{d}}</option>
{% endfor %}
</select>
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
You can use redirect(...) instead of just calling the function.
from flask import redirect
...
if request.method == "POST":
run_dir = request.form.get("run_list")
run_path = dir_loc + "/" + run_dir
return redirect(url_for('run', run_path=run_path))
#app.route("/run/<run_path>", methods = ["GET", "POST"])
def run(run_path):
if os.path.isdir(run_path) == True:
...

How to handle three functions with celery in django?

I'm having a three function in my django site views but I can only run one. I have never used celery, can you help me to transform this into the celery tasks?
As you can see, I want to save document which is uploaded by user, and then I want to do some pandas stuff with that file, and after that I want to show pandas stuff in html page.
This is forms.py
class DocumentForm(forms.Form):
docfile = forms.FileField(label='Select a file')
This is views.py
def save_exls(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
return redirect('html_exls')
else:
form = DocumentForm()
documents = Document.objects.all()
context = {'documents': documents, 'form': form,}
return render(request, 'list.html', context)
def pandas_exls(request):
if request.method == "POST":
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
output = io.BytesIO()
newdoc = request.FILES['docfile']
dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0])
writer = pd.ExcelWriter(output)
for name, df in dfs.items():
#pandas stuff
done.to_excel(writer, sheet_name=name)
output.seek(0)
response = HttpResponse(
output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
else:
form = DocumentForm()
return render(request, 'list.html', {'form': form})
def html_exls(request):
if request.method == "POST":
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
output = io.BytesIO()
newdoc = request.FILES['docfile']
dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0])
writer = pd.ExcelWriter(output)
for name, df in dfs.items():
#pandas stuff for html
done.to_excel(writer, sheet_name=name)
html = done.to_html()
print(html)
output.seek(0)
response = HttpResponse(
output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
else:
form = DocumentForm()
return render(request, 'list.html', {'form': form})
This is html file, list.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Django site</title>
</head>
<body>
<!-- Upload form. Note enctype attribute! -->
<form action="{% url "pandas_exls" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload"/></p>
</form>
<br/>
{{html|safe}}
</body>
</html>
I use task_api for this, this is a django project that keeps track of the functions and provides some javascript to poll the backend for a change and updates when the functions are done running.
It does not yet seem to support file parameters, but you could save the file first, and then in javascript call the next method to operate on that file once saved, and display progress.
I would write 3 endpoints, 1 to upload the file, using the form, then 1 ajax endpoint you call in javascript to process the file, this will return when it is done, at which point you can redirect to the 3rd endpoint which will download the file.
e.g.
views.py
from task_api.tasks import Task
from task_api.params import IntParameter, StringParameter
class Pandas(Task):
name = 'pandas'
inputs = {
'documentid': IntParameter(),
}
outputs = {'output': StringParameter()}
def run(self, documentid):
self.progress = 0
output = io.BytesIO()
newdoc = Document.objects.get(id=documentid)
dfs = pd.read_excel(newdoc.docfile, sheet_name=None, index_col=[0])
writer = pd.ExcelWriter(output)
for name, df in dfs.items():
#pandas stuff
self.progress += 1 # update progress so we can show something to user in javascript
done.to_excel(writer, sheet_name=name)
output.seek(0)
Document.done = True
Document.output = output
Document.save()
return documentid
# configure /download in your urls.py to point to this view with documentid parameter
def download_exls(request, documentid):
response = HttpResponse(
Document.objects.get(id=documentid).output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
def save_exls(request):
if request.method == 'POST' and request.is_ajax():
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile=request.FILES['docfile'])
newdoc.save()
return HttpResponse(json.dumps({'documentid': newdoc.id}), content_type="application/json")
else:
form = DocumentForm()
documents = Document.objects.all()
context = {'documents': documents, 'form': form,}
return render(request, 'list.html', context)
and in your list.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Django site</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="{% static 'django-task-api.min.js' %}"></script>
<script type="text/javascript">
function runtask(task, documentid, progressdivname) {
TaskAPI.run(task, documentid, function(json) {
if (json.target === null || json.progress === null) {
return false
}
document.getElementById(progressdivname).innerHTML = 'Progress: ' + json.progress + ' / ' + json.target
})
.then(function(json) {
# panda's is done, download doc
window.location = '/download/' + json.outputs.documentid;
})
return false
}
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "/upload",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(documentid)
{
// process uploaded file.
runtask('pandas', {'documentid': documentid}, 'progress')
}
,
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});
</script>
</head>
<body>
<!-- Upload form. Note enctype attribute! -->
<form action="{% url "pandas_exls" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload"/></p>
</form>
<br/>
<div id="progress"></div>
</body>
</html>
Be advised, this will allow anyone to download any file, just based on the id, you will probably want to add some authentication checks if this is not intended, you might also want to do some garbage collection and cleanup because this will keep all documents in your database.

Update a variable every 5 second using jquery

I am using django to create a webpage and this is the first time I am doing so. I am trying to fetch the value of a variable from .py file at an interval of 5 seconds. Below is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Like Post App</title>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
<div class = "display-3 color-red"><center>DataFlair AJAX Tutorial<br>Post APP</center></div>
{% for post in posts %}
<div class = 'container jumbotron'>
<h3 class="display-5">{{ forloop.counter }}. {{ post.post_heading }}</h3>
<p class="lead">{{ post.post_text }} </p>
<p>
<div type="text/css" class = "container">Author : {{ post.post_author }}</div>
<a class="likebutton btn btn-primary btn-lg" id="like{{ post.id }}" data-catid="{{ post.id }}">Like({{ post.like_ref.counter }})</a> </p> <p id="message{{post.id}}">
</p>
</div>
{% endfor %}
<script type="text/javascript">
setInterval(function() {
getvalue(); // Do something every 5 seconds
}, 5000);
getvalue();
function getvalue(){
var id;
id = $(this).attr("data-catid");
$.ajax(
{
type:"GET",
url: "like",
data:{
post_id: id
},
success: function( data )
{
$( '#like'+ id ).text("Like(" + data +")");
var i=parseInt(data);
console.log("Value= "+i);
}
}
)
}
</script>
</body>
</html>
Below is the views.py code:
import json
from django.shortcuts import render
from .models import Post, Like
from django.http import HttpResponse
# Create your views here.
#DataFlair #AJAX_tutorial
def index(request):
posts = Post.objects.all()
return render(request, 'post/index.html', { 'posts': posts })
def like(request):
if request.method == 'GET':
post_id = request.GET['post_id']
likedpost = Post.objects.get(id = post_id )
m = Like.objects.filter( post=likedpost ).first()
m.counter +=1
m.save()
value1= int(m.counter)
#data1= {'cmd': 'success', 'ctr': str(m.counter) }
return HttpResponse(value1)
#return HttpResponse(json.dumps(data1))
else:
return HttpResponse("unsuccesful")
I keep getting the following errors:
1) GET http://localhost:8000/ajax/like/ 500 (Internal Server Error)
2) GET http://localhost:8000/favicon.ico 404 (Not Found)
Please help.
I believe:
id = $(this).attr("data-catid");
is not pointing to the button... maybe you should try:
id = $(".likebutton").attr("data-catid");

Why is my form trying to submit to the wrong endpoint?

I have a python script and a mongoDB instance.
With flask I now want to list all the items of my database on a webpage and use a second webpage to trigger the script to add an other item.
But everytime I click "submit" on the "/add" page, I get a "Method not allowed" and I can see, that it tries to submit it to "/" instead of "/add" ..
script.py
from flask import Flask, render_template, request
import requests, json, sys, getopt, smtplib
from os import system, name
from pathlib import Path
from pymongo import MongoClient
client = MongoClient(port = 27017)
db = client.amazonProducts
allitems = []
allMyItems = []
for document in db.items.find():
allitems.append(document["name"])
def addItem():
for dbWishList in db.wishlist.find():
url = dbWishList["wishlist"]
items = json.loads(requests.get(url).text)
if items:
for item in items:
itemName = str(item["name"])
itemPrice = item["new-price"]
itemUrl = str(item['link'])
if itemPrice:
itemPrice = str(itemPrice[26: ])
itemPrice = str(itemPrice[: itemPrice.find("<")])
itemPriceF = str(itemPrice.replace(".", ""))
itemPriceF = str(itemPriceF.replace("€", ""))
itemPriceF = str(itemPriceF.replace("\xa0", ""))
itemPriceF = str(itemPriceF.replace(",", ".")).replace("\xf6", "")
itemPriceFi = float(itemPriceF)
itemUrl = itemUrl[: itemUrl.find("?coliid")]
itemNameF = itemName.replace('"', '"')
itemNameFi = itemNameF.replace("&amp;", "&")
itemNameFi = itemNameFi.replace("ü", "ue").replace("ö", "oe").replace("ä", "ae").replace(" ", " ").replace("–", "-")
amazonItem = {
'name': itemNameFi,
'url': itemUrl,
'price': itemPriceFi,
'maxPrice': 0
}
db.items.insert_one(amazonItem)
for document in db.items.find():
allMyItems.append(document["name"])
return allMyItems
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("index.html", len = len(allitems), allitems = allitems)
app.run(use_reloader = True, debug = True)
app.config["DEBUG"] = True
#app.route("/add", methods = ["GET", "POST"])
def secPage():
errors = ""
if request.method == "POST":
global testingVar
testingVar = None
try:
testingVar = string(request.form["testingVar"])
except:
errors += "<p>{!r} is not a string.</p>\n".format(request.form["testingVar"])
if testingVar is not None:
addItem()
return render_template("secIndex.html", len = len(allMyItems), allMyItems = allMyItems)
return '''
<html>
<body>
{errors}
<p>What you wanna do?:</p>
<form method="post" action=".">
<p><input name="testingVar" /></p>
<p><input type="submit" value="Do magic" /></p>
</form>
</body>
</html>
'''.format(errors=errors)
index.html
<!DOCTYPE html>
<html>
<head>
<title>For loop in Flask</title>
</head>
<body>
<ul>
<!-- For loop logic of jinja template -->
{%for i in range(0, len)%}
<li>{{allitems[i]}}</li>
{%endfor%}
</ul>
</body>
</html>
secIndex.html
<!DOCTYPE html>
<html>
<head>
<title>For loop in Flask</title>
</head>
<body>
<!-- For loop logic of jinja template -->
<form method="post" action=".">
<p><input name="testingVar" /></p>
<p><input type="submit" value="Do magic" /></p>
</form>
</body>
</html>
The items are built like:
amazonItem = {
'name': itemNameFi,
'url': itemUrl,
'price': itemPriceFi,
'maxPrice': 0
}
Can anyone here follow me and tell me where my mistake might be?
In your form definition you have:
<form method="post" action=".">
The action attribute needs to have the endpoint you want to send the post request to. In your case, you want
<form method="post" action="/add">
If you omit the action attribute, it will submit the post request to the current page, so if you are viewing your form from /add, you can just use
<form method="post">

Categories

Resources