I have a form on one page that I want to submit to another page. I can't figure out how to create the link to that second page.
Project layout:
Fileserver/
config.py
requirements.txt
run.py
setup.py
app/
__init__.py
static/
css/
img/
js/
templates/
formAction.html
formSubmit.html
index.html
__init__.py:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
ip = request.remote_addr
return render_template('index.html', user_ip=ip)
index.html:
<!DOCTYPE html>
<html lang="en">
<body>
<ul>
<li>Check Out This Form!
</ul>
</body>
</html>
I can see the page at localhost:5000/ without issue.
I have also tried:
as well as:
What am I missing?
url_for generates urls to routes defined in your application. There are no (or should probably not be any) raw html files being served, especially out of the templates folder. Each template should be something rendered by Jinja. Each location you want to display or post a form to should be handled and generated by a route on your application.
In this case, you probably want to have one route to both render the form on GET and handle the form submit on POST.
__init__.py:
from flask import Flask, request, url_for, redirect, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/cool_form', methods=['GET', 'POST'])
def cool_form():
if request.method == 'POST':
# do stuff when the form is submitted
# redirect to end the POST handling
# the redirect can be to the same route or somewhere else
return redirect(url_for('index'))
# show the form, it wasn't submitted
return render_template('cool_form.html')
templates/index.html:
<!doctype html>
<html>
<body>
<p>Check out this cool form!</p>
</body>
</html>
templates/cool_form.html:
<!doctype html>
<html>
<body>
<form method="post">
<button type="submit">Do it!</button>
</form>
</html>
I don't know what your forms and routes actually do, so this is just an example.
If you need to link static files, put them in the static folder, then use:
url_for('static', filename='a_picture.png')
So what I just found was that if I don't wrap the href in parenthesis it works and I also created a link to return back a page
#app.route('/blog')
def blog():
return '<h1>These are my thoughts on <a href=blog/2020/dogs>dogs</a></h1>'
#app.route('/blog/2020/dogs')
def blog2():
return '<h3>these are my dogs <a href=../../blog>home</a></h3>'
Related
I'm trying to show a background image using python flask and html. But I get the error "Failed to load resource: the server responded with a status of 404 (NOT FOUND)" My structre I think is good but heres the code.
home.py file
from flask import render_template, Blueprint, request, send_file
home_page = Blueprint('home', __name__)
#home_page.route('/', methods=['POST', 'GET'])
def home():
return render_template('index.html')
return send_file ("home_bg.jpg")
index.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>poo</title>
<style>
</style>
</head>
<body style="background-image: url(/static/home_bg.jpg);">
<script>
</script>
</body>
</html>
I think it has something to do with returning the picture to the client in the home.py file.
Change the URL to this style
background-image: url({{ url_for('static',filename='img/home.jpg') }})
To learn more about this here is the documentation:
http://flask.pocoo.org/docs/1.0/tutorial/static/
You must change the home view function and remove the last line, because firstly this line will NEVER be executed, and secondly it is simply not necessary, the flask distributes static files itself, you should not do it manually
The line from the template where you upload the image should be changed to the following:
background-image: url( {{ url_for('static', filename='home_bg.jpg') }} )
Also see:
About Static Files
About url_for function
And about url building in flask using url_for
The following code works perfectly from the .py file but I want to separate the HTML and put it in templates/index.html.
I suppose I have to use the render_template function in Flask to be able to return the same results.
# File dynamic_website.py
from owlready2 import *
onto = get_ontology("bacteria.owl").load()
from flask import Flask, url_for
app = Flask(__name__)
#app.route('/')
def ontology_page():
html = """<html><body>"""
html += """<h2>'%s' ontology</h2>""" % onto.base_iri
html += """<h3>Root classes</h3>"""
for Class in Thing.subclasses():
html += """<p>%s</p>""" % (url_for("class_page", iri = Class.iri), Class.name)
html += """</body></html>"""
return html
I created a folder template and a file index.html. I used return render_template('index.html') but it doesn't work. What arguments do I have to add to the return_template function? "for Class in Thing.subclasses():" have to be in the .html file or .py file? What about the url_for function?
If you could edit the .py code and let me know what should I write exactly in the index.html file to have the same results it would be great.
UPDATE:
What I have done:
Python code
from flask import Flask, render_template
from owlready2 import *
from flask import Flask, url_for
onto = get_ontology("bacteria.owl").load()
app = Flask(__name__)
#app.route("/")
def ontology_page():
for Class in Thing.subclasses():
return render_template('index.html')
Html code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>{{ Class.name }}</h1>
</body>
</html>
You can't return a function multiple times. Whatever is returned, is the value of the function. This tutorial is in JS, but it implies the same concept as python does.
If you want the user to see a list of things on the html, do this. render_template('index.html', things=Thing.Subclasses()) This will give Jinja a list, where it can then for loop.
For html you can do this
{% for s in things %} {{ s }} is something {% endfor %}. Do anything you want with the s though, s is one subclass from the list.
I am trying to upload file from my flask site,but it keeps returning the error
method is not allowed for the requested URL. Even my teacher does not have the answer to this question. According to him he has never seen this error. really appreciate your help
my HTML file is as follows
<!DOCTYPE html>
<html lang="en">
<title> Data Collector App </title>
<head>
<link href="../static/main.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Data Collector</h1>
<form action={{url_for('index')}} method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>
Python srcipt is
from flask import Flask, render_template, request, send_file, url_for
import pandas
from werkzeug.utils import secure_filename
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/index')
def upload():
if method == "POST":
file=request.files['file']
file.save(secure_filename("new"+file.filename))
return render_template('index.html')
if __name__ == "__main__":
app.run(debug = True)
Add any allowed methods to a route in the decorator, e.g.
#app.route('/index', methods=['POST', ...])
EDIT:
You should probably also check on the method field of request instead of just method.
if request.method == 'POST':
By default routes only accept the GET method. If you want your route to answer to other methods, pass a custom methods parameter to #app.route as follows
#app.route('/', methods=['GET', 'POST',])
...
#app.route('/index', methods=['GET', 'POST',])
...
Source https://flask.palletsprojects.com/en/1.1.x/quickstart/#http-methods
I am making a web app using Python and have a variable that I want to display on an HTML page. How can I go about doing so? Would using {% VariableName %} in the HTML page be the right approach to this?
This is very clearly explained in the Flask documentation so I recommend that you read it for a full understanding, but here is a very simple example of rendering template variables.
HTML template file stored in templates/index.html:
<html>
<body>
<p>Here is my variable: {{ variable }}</p>
</body>
</html>
And the simple Flask app:
from flask import Flask, render_template
app = Flask('testapp')
#app.route('/')
def index():
return render_template('index.html', variable='12345')
if __name__ == '__main__':
app.run()
Run this script and visit http://127.0.0.1:5000/ in your browser. You should see the value of variable rendered as 12345
Sorry I've searched inside the stackoverflow and googled, but no useful information found.
I have an flask application,
python version 2.6
flask version 0.9
its application hierarchy is like
application/
__init__.py
app.py
hello/
__init__.py
view.py
templates/
hello.html
both files init.py are empty
app.py
-----------------------
from flask import Flask
from flup.server.fcgi import WSGIServer
from hello.view import hello
app = Flask(__name__)
app.debug = True
app.register_blueprint(hello, url_prefix='/hello')
if __name__ == '__main__':
WSGIServer(app, bindAddress='/tmp/app.sock').run()
view.py
-----------------------
import os
from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound
hello = Blueprint('hello', __name__, template_folder='templates')
#hello.route('/')
def get_index():
try:
return render_template('hello.html')
except TemplateNotFound:
abort(404)
hello.html
-----------------------
<!DOCTYPE html>
<html>
<head>
{% block head %}
<meta charset="utf-8">
{% endblock %}
</head>
<body>
<div>
{% block body %}
<h1>Click Me</h1>
{% endblock %}
</div>
</body>
</html>
It works fine when I enter localhost:8080/hello, but turns out error if I click the link in html. I found its url value is href="/hello/hello/" (Should it be /hello/ right?).
I know hello.get_index is mapped to /hello/, but have no idea that the first one hello/ comes from. Any hint is appreciated.
Have you tried removing the url_prefix parameter when you regisger the blueprint? For example, what if you change the following from :
app.register_blueprint(hello, url_prefix='/hello')
to
app.register_blueprint(hello)