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 ..
Related
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.
This question already has answers here:
how to split the string in django template?
(3 answers)
Closed 3 years ago.
I need to perform split() function inside django template tag.
I tried to do this, but its not working
{% for m in us.member %}
{% with mv=((m.split(','))[0].split('='))[1] %}
<h3 class="media-title">
{{ mv }}
</h3>
{% endwith %}
{% endfor %}
Here value of m return a string value
'cn=RND3,ou=Production_test,dc=iss,dc=rndtest,dc=local'
Expected output is RND3
It is not possible to run a raw python code inside the templates in
django.
But then alternatevekly you can create custom template tag which can fulfill your requrement. More you can read here in the offical docs of django
I hope this helps....Thanks :)
This question already has answers here:
Get a variable from the URL in a Flask route
(2 answers)
Can Flask have optional URL parameters?
(11 answers)
Closed 4 years ago.
I need to pass parameter to routes using url_for() function and redirect() I think I did the same. But, I get TypeError: book() missing 1 required positional argument: 'book_title' I know that the parameter book_title is not being recieved by the book() function in my code and thats why the error. But, I dont know what's going wrong behind the scenes.
These are my routes
#app.route('/search/<title>/',methods=['GET','POST'])
def btitle(title):
book_title = db.execute("SELECT title,author,isbn from books WHERE (title LIKE :title)",params={"title":title}).fetchall()
if request.method == 'GET':
#book_title = db.execute("SELECT title,author,isbn from books WHERE (title LIKE :title)",params={"title":title}).fetchall()
if book_title:
return render_template("booktitle.html",book_title=book_title)
else:
return render_template("error.html")
else:
#book_title = db.execute("SELECT title,author,isbn from books WHERE (title LIKE :title)",params={"title":title}).fetchall()
if book_title:
return redirect(url_for("book",book_title=book_title))
#app.route('/books',methods=['GET','POST'])
def book(book_title):
if request.method == 'GET':
return render_template("individualbook.html",book_title=book_title)
And, this is my booktitle.html
{% extends "layout.html" %}
{% block title %}
{{ book }}
{% endblock %}
{% block body %}
<h1>Search results</h1>
<ul>
{% for book in book_title %}
<li>
<a href="{{ url_for('book') }}">
{{ book }}
</a>
</li>
{% endfor %}
</ul>
{% endblock %}
You problem is that the book route is not getting the argument book_title that it expects.
This is because you are defining it like this:
#app.route('/books',methods=['GET','POST'])
def book(book_title)
In flask, if you want your view functions to take parameters you need to include them in the route. In your example this could look like this:
#app.route('/books/<book_title>',methods=['GET','POST'])
def book(book_title)
If you do not put the <book_title in the route, flask will not be able to provide the book_title parameter to the book function which is what it tells you in the error.
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.
This question already has an answer here:
Call python function using HTML
(1 answer)
Closed 8 years ago.
I have a python script (display_names.py) that displays the list of names in the json file
def search():
with open('business_ten.json') as f:
data=f.read()
jsondata=json.loads(data)
for row in jsondata['rows']:
a=str(row['name'])
yield a
print list(search())
I am trying to call this function in my html file(crawl.html) using flask.
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Rating app<h2>
<h3>This is the home page for the Rating app<h3>
</div>
<body>
<p>{{ myfucntion}}</p>
</body>
{% endblock %}
My routes file is as follows:
from flask import Flask,render_template
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
#app.route('/crawl')
def crawl():
return render_template('crawl.html' , myfucntion=search)
if __name__ == '__main__':
app.run()
This doesnt work and it always gives an error on the html page
please help
I believe you need to execute the function when calling it. In python, to execute a function, you use parentheses, so try:
{{ myfucntion() }}
Edit: I see you typoed them both, so that was not an issue. My apologies.