Passing dynamic value from HTML to Python Flask [duplicate] - python

This question already has an answer here:
Reference template variable within Jinja expression
(1 answer)
Closed 7 years ago.
I need to pass dynamic values to my python view. My HTML looks like:
<a href="{{ url_for('refresh_page',
lang_code=g.current_lang,
feature='a+z+',
cata={{ att.get('url_slug')}})}}"
>
I need to pass this {{ att.get('url_slug')}} to my Flask View:
#app.route('/<lang_code>/category/<string:feature>/<string:cat>/<int:pag e>')
def navigate_page(feature, page):
But its not working. I just started working on views, what I am doing wrong. Please help!!

The url_for is already a template function, so no need to escape the parameter:
<a href="{{ url_for('refresh_page',
lang_code=g.current_lang,
feature='a+z+',
cata=att.get('url_slug')) }}">

Related

Create http query in Flask Python [duplicate]

This question already has answers here:
Create dynamic URLs in Flask with url_for()
(6 answers)
Closed 2 months ago.
I am trying to work with querys in Flask. I have a page choose.html where you can click buttons. these should be sent in a query then to page 2. So page 2 should be rendered by Flask with the query e.g.
127.0.0.1/login?username=test&color=3
I have tried the following so far (hard coded):
<button class="continue" id="submit" name="submit">Continue</button>
#app.route('/login', methods=['post', 'get'])
def login():
message = request.args.get('username')
That was the response:
werkzeug.routing.BuildError: Could not build url for endpoint 'login?username=test'. Did you mean 'login' instead?
Found out the answer:
{{ url_for('login', user='foo', name='test') }}
This will create a query like this:
http://127.0.0.1:10000/login?user=foo&name=test

Flask and Retrieving data from HTML [duplicate]

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 1 year ago.
i am relatively new to Flask/Python/HTML so please excuse my language.
Basically I am trying to retrieve the "name" field with request.form.get that was inputted in my HTML page. The name field was generated with a for loop in jinja. When i hit the checkbox, and click submit, i expect the request.form.get to retrieve the "name" field that was in that specific check boxes' data. However, when i test out the data, I get a 404 error that says NONE for the request.form.get value. I'm not sure where I am going wrong. I suspect it might be what I am plugging in as the name for request.form.get.
On my flask side:
#app.route("/recipedata", methods=["GET","POST"])
def recipedata():
if request.method == 'POST':
food = request.form.get("{{value.id}}")
On HTML side:
{% for value in foodinfo.results %}
<form action="/recipedata" method = "POST">
<input type="checkbox" name="{{value.id}}" value={{value.id}}>
<input type=text placeholder="{{value.id}}">
<input type="submit"> Go to Recipe info
</form>
{% endfor %}
The 2nd line in my form tag with type text was used to test whether my value.id was printing correctly in Jinja, and indeed it was. Additionally, for clarification, foodinfo is passed as a .json() object with nested dictionary key/values. Value.id allows me to access that dict's value at key 'id', I believe.
Thank you!
I don't think your function definition of recipedata() is valid as per python syntax. You need to indent code in python to preserve scope information. You can see more here.
Try with following function definition.
def recipedata():
if request.method == 'POST':
food = request.form.get("{{value.id}}")
I'm not sure if HTML part is causing any trouble.

cannot pass variable with url_for flask, python, html5

I was trying to put a link in some text through url_for (flask, python3) and also pass a variable but nothing I tried worked .Here's the code I used. Am I doing something wrong?
html5:
<a class="mr-2" href={{ url_for('user','username'=posts.author)}} >TEXT</a>
python3:
#app.route('/user')
def user(username):
print(username)
You'd need to change the template code to look like:
<a class="mr-2" href="{{ url_for('user',username=posts.author) }}" >TEXT</a>
However you'd also have to change the python code for this to be valid:
#app.route('/user/<username>')
def user(username):
print(username)
A valid request is now:
/user/CodEdo
Which is the URL which should be rendered in the href assuming that posts.author in the template is CodEdo.

Accessibility of Session variable in Jinja2 with different name [duplicate]

This question already has answers here:
How to access session variables in jinja 2 - Flask
(3 answers)
Pass variables to all Jinja2 templates with Flask
(2 answers)
Global variables in Flask templates
(1 answer)
What happens when you assign the value of one variable to another variable in Python?
(10 answers)
In Jinja2, how do you test if a variable is undefined?
(9 answers)
Closed 3 years ago.
I want to show different header for person with logged in and person who logged out in Flask. Could I use the session variable directly in the jija2 template.
I have used different name for session since , another session variable name used for sqlalchamy session.
from flask import session as usersession
I have tried accessing the usersession variable but it's saying undefined. but when I use the session['username'] I could access the session variable.
further when I pop from usersession It's not popping from the session. Still session accessed in the tamplete has the username variable
usersession.pop('email', None)
usersession.pop('type', None)
jinja2.exceptions.UndefinedError: 'usersession' is undefined
My code is below .
{% if usersession['username'] is not none %}
{% include "store/headers/loginheader.html" %}
{% else %}
{% include "store/headers/logoutheader.html" %}
{% endif %}
In your views function, try usersession[‘username’] = ‘username
And in the template:
{{ usersession[‘username’] }}
For sessions make sure you have set up the environment correctly to be able to access sessions (ie a secret key).
Also have a look at flask-login as their ‘current_user’ object has great functionality and may be what you’re looking for

Flask and HTML Variables [duplicate]

This question already has answers here:
Passing HTML to template using Flask/Jinja2
(7 answers)
Closed 4 years ago.
I'm new to flask, but want to integrate some HTML capabilities from other libraries together with the templating power of flask. In playing around with variables, I'm not able to understand the different behavior for rendering HTML. Sometimes I can get the HTML rendered if I pass it directly to a view as a variable:
body = a bunch of HTML
#app.route('/')
def index():
return '''
{}
'''.format(body)
However, if I try to pass this to a template using the {{ body }} variable, I don't get the HTML rendered. Instead, I will see the raw HTML on the page.
#app.route('/')
def index():
return render_template("index.html", b = body)
In the "index.html" file, I call this with the {{ b }} template syntax. Here, I get the raw HTML though. I feel there's just one little piece I'm missing. Here's what I see for each approach respectively.
Jinja will escape all strings that it parses to avoid accidentally injecting HTML into your templates. To mark variables as "safe to use as-is", you need to use the safe template filter.
{{ b|safe }}
>>> b = 'Example'
>>> render_template_string('{{ b }}', b=b)
'<a href="#">Example</a>'
>>> render_template_string('{{ b|safe }}')
'Example'

Categories