Dynamic Flask Checkbox Form Composition with WTFlask - python

I am having some trouble applying the code in the WTForms documentation to my use case (see "Dynamic Form Composition" section). My goal is to use a list of strings (list_a, of variable length) as an argument to produce a series of checkbox forms. For example, if list_a = ['one, 'two'], then the output would be a form with two checkboxes labeled "one" and "two". The documentation says to use this:
def my_view():
class F(MyBaseForm):
pass
F.username = StringField('username')
for name in iterate_some_model_dynamically():
setattr(F, name, StringField(name.title()))
form = F(request.POST, ...)
# do view stuff
and in my attempt to appropriate it, I've come up with this:
def wrapper_func(list_a):
class Prefs(FlaskForm):
pass
for ele in list_a:
setattr(Prefs, ele, BooleanField(ele) )
form = Prefs(request.POST, ...)
Can anyone help me clean this up to get it to work? I'm not sure what else goes in the last line, or if a list is even allowed in this context. Any input would be greatly appreciated!

Based on your question it's hard to decide whether you are using WTForms or Flask-WTF. The documentation link points to the former, while your example uses the FlaskForm class, which is part of the latter.
The following minimalistic example is made using WTForms.
Project structure:
your_project_folder
├───forms
│ ├───__init__.py
│ └───dynamic_form.py
├───templates
│ └───main.html
├───venv
│ └───your_virtual_environment_files
└───server.py
dynamic_form.py contains your wrapper function without the form instantiation (it just returns the dynamically created form class):
from wtforms import Form, BooleanField
def wrapper_func(list_a):
class Prefs(Form):
pass
for ele in list_a:
setattr(Prefs, ele, BooleanField(ele))
return Prefs
main.html contains the HTML code with Jinja2 syntax to generate the form:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="POST">
{% for field in form %}
<div>{{ field.label }}: {{ field }}</div>
{% endfor %}
<button type="submit">Submit</button>
</form>
</body>
</html>
server.py puts everything together:
from flask.app import Flask
from flask import request, render_template, redirect
from forms.dynamic_form import wrapper_func
app = Flask('form_app')
#app.route('/', methods=['GET', 'POST'])
def main():
input_list = ['one', 'two', 'three'] # generate it as needed
prefs = wrapper_func(input_list)
form = prefs(request.form)
if request.method == 'POST' and form.validate():
# do your logic with the submitted form data here
return redirect('/')
return render_template("main.html", form=form)
if __name__ == '__main__':
app.run(host='localhost', port=3456, debug=True)
The last two lines are strictly for development purpose!
Please let me know if this example helps!

Related

Using Flask, html page showing up blank

So trying to finish a lab using Flask Templates
Here is my python code:
cryptosnapshots = (requests.get(f"https://api.finage.co.uk/snapshot/crypto?quotes=false&trades=true&symbols=&apikey=XXX")).json()
snapshot = (cryptosnapshots['lastTrades'][:20])
#app.route('/crypto_data', methods = ['GET']) # define the first route, the home route
def show_crypto(): # define the function that responds to the above route
if request.method == 'GET':
return render_template('show.html', snapshot = snapshot)
if __name__ == '__main__':
app.run()
and here is my the code from the html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{% for snapshot in snapshots %}
<h2>Symbol: {{snapshot['s']}}</h2>
<p> Last Price: {{snapshot['p']}}<p>
{% endfor %}
</body>
</html>
When python returns the url and I add my "/crypto_data" endpoint, the page just shows up blank...is my error on the python side or the html side (or is it the api??)?
TIA!
Im expecting the url and endpoint to lead to an html list of all the last trading price from the first 20 cryptos on the list.
My first issue was breaking down the API json and I thought once that was solved it would be a breeze...
labs due Sunday, someone help lol
In the Jinja template, your are accessing a value name snapshots. But in your Flask code, you are defininig a value name snapshot.
Try replacing the value named snapshot by snapshots in your Flask app:
cryptosnapshots = (requests.get(f"https://api.finage.co.uk/snapshot/crypto?quotes=false&trades=true&symbols=&apikey=XXX")).json()
snapshot = (cryptosnapshots['lastTrades'][:20])
#app.route('/crypto_data', methods = ['GET']) # define the first route, the home route
def show_crypto(): # define the function that responds to the above route
if request.method == 'GET':
return render_template('show.html', snapshots = snapshot)
if __name__ == '__main__':
app.run()

Python Template Variables not recognised in IDE (Pycharm)

New to Python Flask and trying to work out some ideas I have learned.
I am working with Pycharm but it seems that template variables and template tags (such as {% for %}) are not recognised.
My goal is to pass some data into the HTML file and iterate through a list variable.
Already tried to install different packages such as Django, Jinja2 and more. But no luck.
Code Below:
from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
app = Flask(__name__)
app.config["SECRET_KEY"] = "Key"
my_list = ["One", "Two", "Three"]
#app.route("/", methods=["GET", "POST"])
def index():
return render_template('index.html', my_list=my_list)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>My List<h1>
{% for items in my_list %}
<li>items</li>
{% endfor % }
</body>
</html>
Also note my import statements. Maybe i missed one?
Hope all clear.
Cheers
Kenny.
You have to use {{ ... }} expression in Jinja to get the variable output.
Change <li>items</li> to <li>{{ items }}</li> in your Jinja for loop.

Calling python function in html page

Ive made a flask script which runs fine however im trying to display some values in a table on another html page which for some reason is not happening.
i've already tried going through jinja2 documentation and a few other answers but it didn't help much.
the flask file.py
from flask import Flask,render_template,request
app = Flask(__name__)
from webscraper import keeda,display_tbl
#app.route('/', methods=['POST', 'GET'])
def scraper():
if request.method == 'POST':
url = request.form['url']
df=keeda(url)
return render_template(('completed.html',display_tbl(df)))
else:
return render_template('index.html')
if __name__ == '__main__':
app.run()
the completed.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Summary of Scraped Data</title>
</head>
<body>
<h1>This is what you got! </h1>
<div>
{{ display_tbl(df) }}
</div>
</body>
</html>
here's the error: jinja2.exceptions.UndefinedError: 'display_tbl' is undefined
i wanted to display a table with values on this page.
You are expecting more than what jinja2 can do for you. Please understand jinja2 is just a way to render templates which are eventually html and javascript, nothing fancy. So, in your case you cannot pass a Python function to your jinja2 template and expect that to run fine. What you can do here is to pass the data returned by display_tbl while rendering template like this:
def scraper():
...
return render_template(('completed.html', data=display_tbl(df))) # data= is important because this is how you are going to access your data in the template
…
def display_tbl(df):
… # Here you should be returning the data you want to display - a list or dict
In the template
<html>
<head>
<meta charset="UTF-8">
<title>Summary of Scraped Data</title>
</head>
<body>
<h1>This is what you got! </h1>
<div>
{{ render_data() }}
</div>
<script>
var d = data | tojson
function render_data() {
// implement the logic to handle how your data should be rendered
}
</script>
</body>
</html>
This is just a rough idea but as you can see you need to change the way you are perceiving jinja2 templates and their interaction with Python or Flask backend.

Error when trying to render Folium map on Django Server

view.py
map = folium.Map(location=[df['latitude'].mean(),
df['longitude'].mean()],tiles="cartodbpositron",zoom_start=12)
map.save("map.html")
context = {'my_map': map}
return render(request, 'my_map.html', context)
my_map.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ my_map }}
</body>
browser result:
folium.folium.Map object at 0x7f49d85662b0
im not sure how to approach getting the html/js to work on the browser after the user has submitted their input via the previous html form...
I have seemed to look everywhere and there are a lot of similar problems with solutions but I could not get any to work!
Thanks!
This response is here to increase the google coverage for others who, like me, also experienced this problem when trying to render a Folium map within a Django template.
Your Code
Please see the comments inside each code block for how to render the map as expected.
views.py
map = folium.Map(location=[df['latitude'].mean(),
df['longitude'].mean()],tiles="cartodbpositron",zoom_start=12)
map.save("map.html")
# {'my_map': map} will output the object, which is what you are seeing
# to rectify this we need to turn it into an iframe which
# the template can then render.
context = {'my_map': map} # change to {'my_map': map._repr_html_()}
return render(request, 'my_map.html', context)
Template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
# after making the change in our views.py this will return the html but
# the template will not render it as expected because it is being escaped.
# You must declare it 'safe' before it will be rendered correctly.
{{ my_map }} # change to {{ my_map | safe }}
</body>
For more information see the Folium doc page here or this SO post.
Hope that helps.
Map objects have a render method which render its html representation.
You can try directly:
<body>
{{ my_map.render }}
</body>
Or you can use the Map.render method to implement a custom inclusion tag, that way you can pass arguments to the render method. See this for reading more about inclusion and custom tags.
# The template tag.
for django.template import Library
register = Library()
#register.inclusion_tag
def render_map(map_object, **kwargs):
return map_object.render(**kwargs)
In your template:
<body>
{% render_map my_map some_arg1=arg1 some_arg2=arg2 %}
</body>

How can I read request values received with Python?

I want to make a simple python script to be run in my server. What it's supposed to do is receive requests and return values according to requests it received.
I want to access the script with a way like http://example.com/thescript.py?first=3&second=4.
and make the script to read the first and second and to do jobs with the values.
How could I do this?
The easiest way is to use Flask:
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def index():
first = request.args.get('first')
second = request.args.get('second')
return render_template('index.html', first=first, second=second)
if __name__ == '__main__':
app.run()
And the template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
First: {{ first }}
<br />
Second: {{ second }}
</body>
</html>
This code will simply print the two parameters provided.

Categories

Resources