Creating Dynamic Url in HTML for Flask Application [duplicate] - python

This question already has answers here:
Create dynamic URLs in Flask with url_for()
(6 answers)
Closed 8 months ago.
I am trying to creating dynamic url in html and routing all "orders/<key_id[0]>" to flaks app.
On the browser hyperlink should be link to name but it should route as "orders/<key_id[0]>"
Tried a lot of thing couln't manage to generate href with key_id variable with it.
Trying to create something like
{{key_id[0]}<p>{{name[0]}}</p></td>
My Base Html Code:
{% for name, sample, date, coord_x, coord_y, key_id in zipped_ %}
<tr>
<td><p>{{name[0]}}</p></td>
<td>{{sample[0]}}</td>
<td><span class="badge badge-danger">{{date[0]}}</span></td>
<td>
<div class="sparkbar" data-color="#00a65a" data-height="20">{{coord_x[0]}},{{coord_y[0]}}</div>
</td>
</tr>
{% endfor %}
Flask App Routing:
#views.route('/orders')
#views.route('/orders/<key_id>', methods=['GET', 'POST']) # ordersda birşey yazdın ama indexten bir post ya da get gelmiyor sanki
def orders():
print(key_id)
#mycursor.execute("SELECT * FROM processed_data WHERE primary_key IN (%s)",(key_id))
#zip_q = mycursor.fetchall()
return render_template("orders.html", zip_q=zip_q)

There are many ways to do it depending on your Jinja version. The "most compatible" one is to use string formatting with urlencode filter
{{key_id[0]}<p>{{name[0]}}</p>

I have found the answer at last.
<a href= {{ url_for('views.orders' , key_id=key_id[0]) }} <p>{{name[0]}}</p></a></td>
with url_for i can dynamically edit the link and for passing variable to flask:
#views.route('/orders')
#views.route('/orders/<key_id>', methods=['GET', 'POST'])
def orders(key_id):
print(key_id)
i can get the key_id variable in the flask app.

Related

Flask Printing Post Data in Browser [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 days ago.
Improve this question
Hope you are all well!
I am very new to Flask and can't seem to wrap my head around some key elements.
The project I am working on is based on this youtube documentation : Subscribe to Push Notifications
Is there any way to print the received POSTed data into the browser?
Here is the app, so far :
from flask import Flask, render_template, request
import xmltodict
app = Flask(__name__)
#app.route("/result", methods=['POST', 'GET'])
def result():
if request.method == 'POST':
result = xmltodict.parse(request.data)
return render_template("table.html", result = result)
if __name__ == "__main__":
app.run(debug=True)
Here is the Table.html in case
<!doctype html>
<html>
<body>
<table border = 1>
{% for key, value in result.items() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body></html>
So far, I have tried a lot of different searches everywhere online but I can't seem to find a way to make this work.

How do I get JSON data when the key has spaces in it using python and flask?

I am using a Queensland government API. The format for it is JSON, and the keys have spaces in them. I am trying to access them with python and flask. I can pass through the data required to the HTML file yet cannot print it using flask.
{% block content %}
<div>
{% for suburb in data %}
<p>{{ suburb.Age }}</p>
<p>{{ suburb.Manslaughter Unlawful Striking Causing Death }}</p>
{% endfor %}
</div>
{% endblock content %}
Above is the code for the HTML file. "Manslaughter Unlawful Striking Causing Death" is the key I am trying to access but it comes up with this error when I load the page.
from flask import Flask, render_template
import requests
import json
app = Flask(__name__)
#app.route('/', methods=['GET'])
def index():
req = requests.get("https://www.data.qld.gov.au/api/3/action/datastore_search?resource_id=8b29e643-56a3-4e06-81da-c913f0ecff4b&limit=5")
data = json.loads(req.content)
print(data)
district=[]
for Districts in data['result']['records']:
district.append(Districts)
return render_template('index.html', data=district)
if __name__=="__main__":
app.run(debug=True)
Above now is all the python code I am running.
The error that is shown on the webpage when trying to load it.
Any suggestions, please?
Instead of using dot notation in your template, you can access values in a dictionary like this
{{ suburb['Manslaughter Unlawful Striking Causing Death'] }}
Hopefully that solves your issue!
In jinja2 (which is used by Flask for templating) you can access dict elements like in python, consider following example:
import jinja2
temp = jinja2.Template("Value of abc is {{data['a b c']}}")
data = {'a b c': '1 2 3'}
rend = temp.render(data=data)
print(rend)
output
Value of abc is 1 2 3

Flask url_for not working with parameters [duplicate]

This question already has answers here:
Get a variable from the URL in a Flask route
(2 answers)
Closed 2 years ago.
I have a function which takes 1 parameter however it seems, my url_for isn't working for some reason
python code
#app.route('/news')
def news(top):
client = gnewsclient.NewsClient(language='english',
location='india',
topic=f'{top}',
max_results=50)
news_list = client.get_news()
topics = client.topics
return render_template('news.html', data=news_list, data2=topics)
Html Code where url_for is being used
home.html
News
news.html
{% for item in data2 %}
<a id="link" href="{{url_for('news', top= item)}}">
<div id="topic" style="color: white">{{item}}</div>
</a>
{% endfor %}
you are missing the parameter top in the route decorator since news(top) view has already a top parameter
#app.route('/news/<top>') # -- HERE --
def news(top):
[..]
return ..

Iterating multiple lists in parallel with Python inside HTML (Flask)

I am building a python web app hosted on pythonanywhere following this tutorial loosely. I am modifying the resulting application to fit my own goal.
Here is my python code that I am using to pass variables to a HTML document in order for them to be added to a table using a for loop:
from flask import Flask, redirect, render_template, request, url_for
app = Flask(__name__)
app.config["DEBUG"] = True
productnames = []
reviews = []
#app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template("main.html", reviews=reviews, productnames=productnames)
reviews.append(request.form["review"])
productnames.append(request.form["products"])
return redirect(url_for('index'))
Using the following code within my HTML, I am looping through that list and adding each item to the table:
{% for review in reviews %}
<tr>
<td></td>
<td>{{ review }}</td>
<td></td>
</tr>
{% endfor %}
And this works, however, I am trying to iterate through multiple lists and found various statements saying that the zip function was what I was looking for so I changed my HTML code to the following segment and it no longer works.
{% for review, product in zip(reviews, productname) %}
<tr>
<td>{{ product }}</td>
<td>{{ review }}</td>
<td></td>
</tr>
{% endfor %}
From python anywhere, the error page says "Error code: Unhandled Exception", and the error log through the pythonanywhere dashboard says:
2018-04-24 12:57:23,957: File "/home/FdScGroup/cloudapp/templates/main.html", line 43, in top-level template code
2018-04-24 12:57:23,957: {% for review, product in zip(reviews, productnames) %}
How do I get this to work?
Any help appreciated, thank you.
zip() is a python function, not a function to be executed in the template language of Flask (Jinja2).
So apply zip() in the view and pass the result to the template:
return render_template("main.html", reviews_products=zip(reviews, productnames))
Then apply this trick:
how to iterate over a list of list in jinja
in the template.

AngularJS with Python flask [duplicate]

This question already has answers here:
Is it possible to use AngularJS with the Jinja2 template engine?
(2 answers)
Closed 4 years ago.
I'm using flask to render index page
app = Flask(__name__)
#app.route("/")
def main():
return render_template('index.html')
I'm sending the results in an ajax call made to an flask REST API. I'm able to build table using Jquery but If I'm using angularjs ng-repeat for a table like below
<table>
<tr data-ng-repeat="r in regResults">
<td>{{r.TCID}}>
</tr>
</table>
I'm getting the below error
[2018-01-30 16:50:32,833] ERROR in app: Exception on / [GET]
UndefinedError: 'r' is undefined
That's because Angular and Jinja2 use {{}} as template tags to print out variables. Jinja2 processes the template before it's rendered by the browser (and eventually picked up by Angular). The simplest solution is to enclose the block in {% raw %} like this:
{% raw %}
<table>
<tr data-ng-repeat="r in regResults">
<td>{{r.TCID}}>
</tr>
</table>
{% endraw %}
This tells jinja2 not to interfere with that section of the template.
If you find yourself with too many {% raw %} tags it might be time to separate your frontend from the backend and communicate over an API.

Categories