I'm basically trying to follow this tutorial ( http://net.tutsplus.com/tutorials/python-tutorials/an-introduction-to-pythons-flask-framework/)
Now when the css part comes in, and i copy the code it simply wont come out styled even afterr main.css is added it still shows up unstyled like if it wasn't importing the css file here's the HTML code
<!DOCTYPE html>
<html>
<head>
<title>Flask</title>
<strong><link rel="stylesheet" type"text/css" href="{{ url_for('static', filename='css/main.css') }}"></strong>
</head>
<body>
<header>
<div class="container">
<h1 class="logo">Flask App</h1>
</div>
</header>
<div class="container">
{% block content %}
{% endblock %}
</div>
</body>
</html>
layout.html ^
Home.html v
{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Flask app<h2>
<h3>This is the home page for the Flask app<h3>
</div>
{% endblock %}
routes.py v
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
This is probably due to the directory structure of your app. By default, flask looks for the static directory in the same level as the file that the app object is created in. This is the example structure for a small application from the flask docs.
/yourapplication
/yourapplication.py
/static
/style.css
/templates
layout.html
index.html
login.html
You can also change the location of the static files by setting the "static_folder" attribute on the app object. Check the docs here for setting the static_folder
Related
so I have made a website using Flask which was working perfectly fine until today when I tried to create a python virtual environment. Does anyone know what could have happened? This is the code for my python file.
from flask import Flask, render_template
app = Flask(__name__, template_folder='html_scripts')
#app.route('/home/')
def home():
return render_template('html_scripts')
#app.route('/about/')
def about():
return render_template('html_scripts')
if __name__ == '__main__':
app.run(debug = True)
This is the code for my main html file:
<!DOCTYPE html>
<html>
<head>
<title>Flask App</title>
<link rel="stylesheet" href="{{url_for('static',filename='css/main.css')}}">
</head>
<body>
<header>
<div class="container">
<h1 class="logo">Adrian's web app</h1>
<strong><nav>
<ul class="menu">
<li>Home</li>
<li>About</li>
</ul>
</nav></strong>
</div>
</header>
<div class="container">
{%block content%}
{%endblock%}
</div>
</body>
</html>
And these are the remaining 2 files(home_page.html and about.html):
{%extends 'layout.html'%}
{%block content%}
<div class = 'home'>
<h1>My homepage</h1>
<p>This is my homepage</p>
</div>
{%endblock%}
and,
{%extends 'layout.html'%}
{%block content%}
<div class = 'about'>
<h1>My about page</h1>
<p>This is my about page</p>
</div>
{%endblock%}
Please do help if you kow how because I have not seen anyone with this problem yet and I can't solve it myself.
Thanks!
In render_template, try using the actual html files. The code below fixes your problem
from flask import Flask, render_template
app = Flask(__name__, template_folder='html_scripts')
#app.route('/home/')
def home():
return render_template('/home_page.html')
#app.route('/about/')
def about():
return render_template('/about.html')
if __name__ == '__main__':
app.run(debug = True)
If use virtual environment You must :
first active virtual environment
go to directory app.py file
run python app.py
For example: my project flask in this path D:\MyProjects\MyflaskApp first active virtualEnviorment then :
(my_env) E:\virtualEnc> cd "D:\MyProjects\MyflaskApp"
(my_env) D:\MyProjects\MyflaskApp>python app.py
* Serving Flask app '__name__'
* Debug mode: off
app.py :
app = Flask(__name__)
OK
So you didn't like my last question
Here is a SECOND question, with much more information than actually needed. It's a very simple problem defining the base dir inside the flask-bootstrap module. If you managed to see my last question, I showed my code, but here is some more of the USELESS information you wanted for some odd reason:
Index.html
{% extends 'bootstrap/base.html' %}
<!-- TEST THINGS ON A DIFFERENT REPL! -->
<!DOCTYPE html>
<html>
<head>
<!-- This is for the tab -->
<title>Helliott-chip</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- Title on top -->
<h1><center>Helliot-Chip</center></h1>
<p>New User? Click to Register!</p>
<!-- Grey Menu Select -->
<div class="scrollmenu1">
{% if current_user.is_anonymous %}
Login
{% else %}
Logout
Profile
{% endif %}
Home
About
Explore
Videos
Music
</div>
{% block content %}
<h1>Hi, {{ current_user.username }}!</h1>
{% endblock %}
{% block app_content %}{% endblock %}
{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{% endblock %}
</body>
</html>
init.py
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from config import Config
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
app = Flask(__name__)
Bootstrap(app)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
mail = Mail(app)
moment = Moment(app)
from app import models, errors
So now that I have that down, my error (after I changed the index to base in the index.html):
[2021-04-13 17:18:39,365] INFO in debughelpers: Locating template "index.html":
1: trying loader of application "app"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /home/runner/Website30/app/templates
-> found ('/home/runner/Website30/app/templates/index.html')
2: trying loader of blueprint "bootstrap" (flask_bootstrap)
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates
-> no match
[2021-04-13 17:18:39,372] INFO in debughelpers: Locating template "bootstrap/base.html":
1: trying loader of application "app"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /home/runner/Website30/app/templates
-> no match
2: trying loader of blueprint "bootstrap" (flask_bootstrap)
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates
-> found ('/opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates/bootstrap/base.html')
172.18.0.1 - - [13/Apr/2021 17:18:39] "GET / HTTP/1.1" 200 -
[2021-04-13 17:18:40,173] INFO in debughelpers: Locating template "404.html":
1: trying loader of application "app"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /home/runner/Website30/app/templates
-> found ('/home/runner/Website30/app/templates/404.html')
2: trying loader of blueprint "bootstrap" (flask_bootstrap)
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /opt/virtualenvs/python3/lib/python3.8/site-packages/flask_bootstrap/templates
-> no match
And my error before I changed it:
jinja2.exceptions.TemplateNotFound: bootstrap/index.html
Now this time without having my question being shut down from any answers in general (which I may note is opposing the purpose of this site) What would be wrong here? Is something wrong with the way I'm initializing flask-bootstrap, or is there some command I need to put in the terminal? Feel free to ask questions, and thanks a lot if it's a simple problem I'm missing. And I apologize for any unneeded attitude, I was just disappointed in the person who locked my last question for "not enough information".
There is an issue with the way you are initializing flask-bootstrap. This how you should go about it:
# Your previous imports
from flask_bootstrap import Bootstrap
app = Flask(__name__)
bootstrap = Bootstrap(app)
# ...
Basically, update the line:
Bootstrap(app)
to:
bootstrap = Bootstrap(app)
This is exactly what you have done for the other installed packages too.
Maintain the line {% extends 'bootstrap/base.html' %} in your base template (which is the parent template). Do not change it to {% extends 'bootstrap/index.html' %} This file inherits the styles, layout, features etc from bootstrap's base template.
<!-- base.html -->
{% extends 'bootstrap/base.html' %}
{% block head %}
<!-- Head information goes here -->
{% endblock %}
{% block navbar %}
<!-- Your navbar goes here -->
{% endblock %}
{% block content %}
<!-- flash message goes here -->
{% block app_content %}
<!-- Content from your custom HTML templates will go here -->
{% endblock %}
{% endblock %}
{% block scripts %}
<!-- Your scripts go here -->
{% endblock %}
In your index.html file which inherits your base,html, you will do:
<!-- index.html -->
{% extends 'base.html' %}
{% block app_content %}
<!-- Content goes here -->
{% endblock %}
I am getting jinja2.exceptions.UndefinedError: 'btn' is undefined exception while logging to the localhost. The btn is properly defined but still.. Can I plaese get the help as soon as possible. Thank You in Advance
Python code- This code is the Python Code
from flask import Flask, render_template, request, send_file
from flask_sqlalchemy import SQLAlchemy
from send_email import send_email
from sqlalchemy.sql import func
from werkzeug import secure_filename
app=Flask(__name__)
#app.route("/")
def index():
return render_template("index.html")
#app.route("/success", methods=['POST'])
def success():
global file
if request.method=='POST':
file=request.files["file"]
file.save(secure_filename("uploaded" + file.filename))
with open("uploaded"+file.filename,"a") as f :
f.write("This was added later!")
return render_template("index.html", btn="download.html")
#app.route("/download")
def download():
return send_file("uploaded" + file.filename, attatchment_filename="yourfile.csv", as_attatchment=True)
if __name__ == '__main__':
app.debug=True
app.run()
HTML-
Index file - This is the main file
<!DOCTYPE html>
<html lang="en">
<title> Data Collector App</title>
<head>
<link href="../static/main.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Collecting Height</h1>
<h3>Please Fill the Entries to get Population Statistics on Height</h3>
<div class="message">
{{text | safe}}
</div>
<form action="{{url_for('success')}}" method="POST" enctype="multipart/form-data">
<input type="file" name="file" > <br>
<button type="submit">Submit</button>
</form>
{%include btn ignore missing%}
</div>
</body>
</html>
Download file- This is the html file for downloading. After importing the file this html code will create a button in the same index.html page so that I can also downoad the same file
<!DOCTYPE html>
<html lang="en">
<div class="download">
<button class="btn"> Download </button>
</div>
</html>
Was facing the same issue. My workaround was to replace:
{% include btn ignore missing %}
with
{% if btn %}
{% include btn %}
{% endif %}
This should work:
{% include [btn] ignore missing %}
The reason for change is due to a Flask update from the time when that video was created
I am trying to build an "enterprise grade" version of a flask app so am using blueprints and a fancy directory structure. I have a "toy" version of this app where everything is in a very flat directory structure with no blueprints and it works.
I have a route program that calcs some variables then passes them to render_template to generate html. The html displays in the browser but all of the variables appear to be set to NONE.
My app uses blueprints and SQLite3.
I have tried multiple things to isolate the error.
Make a textual change to html template to ensure the right template is being picked up. It is.
Pass trivial string variable to html template and see if they show up, they don't.
View source of rendered html, there is nothing where the flask variable names {{ x }} occur in the html template, including the {{ x }} text itself. So it appears the value None has been been used.
Test the code leading up to the render_template, it works perfectly.
My directory structure is: -
\myapp
app.py
\app
__init__.py
\main
__init__.py
routes.py
...
\meta
__init__.py
routes.py
...
\templates
...
base.html
index.html
The code in \meta\routes.py (which corresponds to the meta blueprint) works down to and including entitys = stmt.fetchall() and is: -
from flask import Flask, render_template, request
import sqlite3 as sql
from app.meta import bp
from app import Config
config = Config()
metafile = os.path.join(config.META_DIR, config.META_MS, config.META_DB)
#bp.route('/', methods=['GET', 'POST'])
#bp.route('/index', methods=['GET', 'POST'])
def index():
meta = sql.connect(metafile)
stmt = meta.cursor()
stmt.execute("SELECT * FROM [meta.Entity]")
entitys = stmt.fetchall()
return render_template("index.html", entitys = entitys)
In case it is relevant here is \meta\__init__.py: -
from flask import Blueprint
bp = Blueprint('meta', __name__)
The template html is as follows. The base.html is: -
<!doctype html>
<html>
<head>
{% if title %}
<title>{{ title }} - Metapplica</title>
{% else %}
<title>Metapplica</title>
{% endif %}
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{ url_for('static', filename = 'w3.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename = 'style.css') }}">
</head>
<body>
<div>
Home
</div>
<hr>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
</body>
</html>
and index.html is: -
{% extends "base.html" %}
{% block content %}
<h2>Entities</h2>
<table border = 1>
<thead>
<td>Entity</td>
<td>Action</td>
</thead>
{% for entity in entitys %}
<tr>
<td>{{ entity["Name"] }}</td>
<td>
List
Add
</td>
</tr>
{% endfor %}
</table>
{% endblock %}
Finally the rendered html is this: -
<!doctype html>
<html>
<head>
<title>Home - Metapplica</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/w3.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div>
Home
</div>
<hr>
<h2>Entities </h2>
<table border = 1>
<thead>
<td>Entity</td>
<td>Action</td>
</thead>
</table>
</body>
</html>
In response to #Tobin's comment I have included the code that (should) be registering the blueprint. I use an application factory.
Here is app\__init__()
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask import Flask, session, redirect, url_for, escape, request, current_app
from config import Config
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
# Register blueprints
from app.errors import bp as errors_bp
app.register_blueprint(errors_bp, url_prefix='/err')
from app.auth import bp as auth_bp
app.register_blueprint(auth_bp, url_prefix='/auth')
from app.meta import bp as meta_bp
app.register_blueprint(meta_bp, url_prefix='/meta')
from app.main import bp as main_bp
app.register_blueprint(main_bp)
return app
and here is the code that calls it: -
from app import create_app
app = create_app()
I suspect that somehow when Flask renders the html template the passed variables are not available to the "flask engine" which is pointing somewhere else.
Nothing fails and there are no error messages.
What am I doing wrong?
I've got a simple flask app, with a templates folder with a bunch of html files that are created by a separate program. I want to (1) serve each of these html files by hitting localhost:8888/<html_filename> and
(2) create a directory with hyperlinks to these endpoints on my main / endpoint.
Thoughts on how I could get a jinja template to create links to those endpoints? Heres what I've been thinking.
Flask App:
#app.route('/')
def index():
reports = [f_name for f_name in os.listdir("templates") if f_name.endswith(".html")]
return render_template("index.html", reports=reports)
#app.route('/<report>')
def render_report(report):
return render_template(report+'.html')
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Report Directory</title>
</head>
<body>
<ul>
{% for r in reports %}
<li>
{{ r }}
</li>
{% endfor %}
</ul>
</body>
</html>
Off the top of my head and not tested in any way define a route along the lines of the following:
#route("/<string:slug>/", methods=['GET'])
def page(self, slug):
if slug_exists_as_a_html_file(slug):
return render_template(slug)
abort(404)
The function (or inline it) )slug_exists_as_a_html_file needs to return True if the slug matches a valid html template file, otherwise false.
To generate your report listing use something like :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Report Directory</title>
</head>
<body>
<ul>
{% for r in reports %}
<li>
{{ r }}
</li>
{% endfor %}
</ul>
</body>
</html>