I am trying to render the file home.html. The file exists in my project, but I keep getting jinja2.exceptions.TemplateNotFound: home.html when I try to render it. Why can't Flask find my template?
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
/myproject
app.py
home.html
You must create your template files in the correct location; in the templates subdirectory next to the python module (== the module where you create your Flask app).
The error indicates that there is no home.html file in the templates/ directory. Make sure you created that directory in the same directory as your python module, and that you did in fact put a home.html file in that subdirectory. If your app is a package, the templates folder should be created inside the package.
myproject/
app.py
templates/
home.html
myproject/
mypackage/
__init__.py
templates/
home.html
Alternatively, if you named your templates folder something other than templates and don't want to rename it to the default, you can tell Flask to use that other directory.
app = Flask(__name__, template_folder='template') # still relative to module
You can ask Flask to explain how it tried to find a given template, by setting the EXPLAIN_TEMPLATE_LOADING option to True. For every template loaded, you'll get a report logged to the Flask app.logger, at level INFO.
This is what it looks like when a search is successful; in this example the foo/bar.html template extends the base.html template, so there are two searches:
[2019-06-15 16:03:39,197] INFO in debughelpers: Locating template "foo/bar.html":
1: trying loader of application "flaskpackagename"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /.../project/flaskpackagename/templates
-> found ('/.../project/flaskpackagename/templates/foo/bar.html')
[2019-06-15 16:03:39,203] INFO in debughelpers: Locating template "base.html":
1: trying loader of application "flaskpackagename"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /.../project/flaskpackagename/templates
-> found ('/.../project/flaskpackagename/templates/base.html')
Blueprints can register their own template directories too, but this is not a requirement if you are using blueprints to make it easier to split a larger project across logical units. The main Flask app template directory is always searched first even when using additional paths per blueprint.
I think Flask uses the directory template by default. So your code should be like this
suppose this is your hello.py
from flask import Flask,render_template
app=Flask(__name__,template_folder='template')
#app.route("/")
def home():
return render_template('home.html')
#app.route("/about/")
def about():
return render_template('about.html')
if __name__=="__main__":
app.run(debug=True)
And you work space structure like
project/
hello.py
template/
home.html
about.html
static/
js/
main.js
css/
main.css
also you have create two html files with name of home.html and about.html and put those files in templates folder.
If you must use a customized project directory structure (other than the accepted answer project structure),
we have the option to tell flask to look in the appropriate level of the directory hierarchy.
for example..
app = Flask(__name__, template_folder='../templates')
app = Flask(__name__, template_folder='../templates', static_folder='../static')
Starting with ../ moves one directory backwards and starts there.
Starting with ../../ moves two directories backwards and starts there (and so on...).
Within a sub-directory...
template_folder='templates/some_template'
I don't know why, but I had to use the following folder structure instead. I put "templates" one level up.
project/
app/
hello.py
static/
main.css
templates/
home.html
venv/
This probably indicates a misconfiguration elsewhere, but I couldn't figure out what that was and this worked.
If you run your code from an installed package, make sure template files are present in directory <python root>/lib/site-packages/your-package/templates.
Some details:
In my case I was trying to run examples of project flask_simple_ui and jinja would always say
jinja2.exceptions.TemplateNotFound: form.html
The trick was that sample program would import installed package flask_simple_ui. And ninja being used from inside that package is using as root directory for lookup the package path, in my case ...python/lib/site-packages/flask_simple_ui, instead of os.getcwd() as one would expect.
To my bad luck, setup.py has a bug and doesn't copy any html files, including the missing form.html. Once I fixed setup.py, the problem with TemplateNotFound vanished.
I hope it helps someone.
Check that:
the template file has the right name
the template file is in a subdirectory called templates
the name you pass to render_template is relative to the template directory (index.html would be directly in the templates directory, auth/login.html would be under the auth directory in the templates directory.)
you either do not have a subdirectory with the same name as your app, or the templates directory is inside that subdir.
If that doesn't work, turn on debugging (app.debug = True) which might help figure out what's wrong.
I had the same error turns out the only thing i did wrong was to name my 'templates' folder,'template' without 's'.
After changing that it worked fine,dont know why its a thing but it is.
You need to put all you .html files in the template folder next to your python module. And if there are any images that you are using in your html files then you need put all your files in the folder named static
In the following Structure
project/
hello.py
static/
image.jpg
style.css
templates/
homepage.html
virtual/
filename.json
When render_template() function is used it tries to search for template in the folder called templates and it throws error jinja2.exceptions.TemplateNotFound when :
the file does not exist or
the templates folder does not exist
Create a folder with name templates in the same directory where the python file is located and place the html file created in the templates folder.
Another alternative is to set the root_path which fixes the problem both for templates and static folders.
root_path = Path(sys.executable).parent if getattr(sys, 'frozen', False) else Path(__file__).parent
app = Flask(__name__.split('.')[0], root_path=root_path)
If you render templates directly via Jinja2, then you write:
ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(str(root_path / 'templates')))
template = ENV.get_template(your_template_name)
After lots of work around, I got solution from this post only,
Link to the solution post
Add full path to template_folder parameter
app = Flask(__name__,
template_folder='/home/project/templates/'
)
My problem was that the file I was referencing from inside my home.html was a .j2 instead of a .html, and when I changed it back jinja could read it.
Stupid error but it might help someone.
Another explanation I've figured out for myself
When you create the Flask application, the folder where templates is looked for is the folder of the application according to name you've provided to Flask constructor:
app = Flask(__name__)
The __name__ here is the name of the module where application is running. So the appropriate folder will become the root one for folders search.
projects/
yourproject/
app/
templates/
So if you provide instead some random name the root folder for the search will be current folder.
I'm a beginner at web dev, I'm currently working on a project, but the javascript file insert.js won't load. The html document, upload.html is inside the public folder, and the javascript is inside the main folder.
I used the following path to link the javascript file,
<script src= "../insert.js"></script>
But it didn't seem to work, so I then tried moving upload.html to the main folder, which is HR and I used the following code,
<script src = "/insert.js"></script>
And this didn't work either, so I then tried moving insert.js to the public folder, and used the same path as I have mentioned above, but, then I couldn't export variables to app.js which is located in the main HR directory.
The image I have attached shows location of the files
I don't get what could possibly cause this, I think I should mention this as well, but I got an error while running my javascript file in node. So I inserted the following code in node_modules/whatwg-url/dist/encoding.js:
const {TextDecoder, TextEncoder} = require("util");
I don't know if this has anything to do with my issue, but I thought I would just mention it.
localhost can only access your public folder, so you have to move insert.js in the public folder and do:
<script src = "index.js"></script>
Also if you have node modules in that javascript file it wont run because it can't run the modules and you would have to use a bundler for that js file like webpack, rollup or snowpack.
I placed my files as
main
index.html
files
service-worker.js
index.js
mycss.css
where I wants to cache the index.js and mycss.css file which is not working. And due to some constraint, I can't put the service-worker.js in parallel to index.html page
Another approach of solving the problem is to set the Service-Worker-Allowed HTTP response header if the scope of service-worker.js is different from the scope of files it wants to work with. This idea helps in applications where URL rewriting is done or the context path for files is not similar to the actual directory structure.
Absolutely yes. Moreover, it is considered to be a standard practice to place similar/related files in their respective folder.
So, in your index.html you could do something like this:
<body>
<script src="/files/mycss.css"></script>
<script src="/files/index.js"></script>
<script src="/files/service-worker.js"></script>
</body>
Yes you can put your files in different folders.
When you want to "connect" your css to the html the path is:
src="files/mycss.css"
Hope this will help you.
my jquery file path is c:\xampp\htdocs\project\resources\assets\js\jquery.min.js
..I have tried like below on my page but jquery file don't included ! What I am wrong ..
{{-- <script src="{{ URL::asset('assets/js/jquery.min.js') }}"></script> --}}
The URL::asset() is a helper function in laravel,
when you use this function it automatically generates the URL path to the
ProjectName/public and you have to specify the remaining path inside the asset method.
So, first you would want to place the css , js , 'images' and 'fonts' files inside your public folder that is in the root directory of your project.
then you can use the asset() or URL::asset() to locate your file.
the standard folder structure looks like this ..
ProjectName/public/css/main.css
ProjectName/public/js/jquery.min.js
etc ..
i think that would work for you .
Add those file in public/ folder like public/assets/js/jquery.min.js
Please make sure you have proper access rights to aforementioned resource (js file). You can also try to view the file with your web browser by visit http://your_hostname/assets/js/jquery.min.js
I have a node.js file server running which (when visited) returns a html content. Also in the same directory of the node.js file, there is a javascript file called test.js. Also in the html content being returned, I need to load that javascript file. However in the html content, being returned, which comes out to be called index.html, the script looks like
<script type="text/javascript" src="test.js"></script>
But the server isn't sending the test.js file, its only sending the index.html file, and the script link is loading it relatively from the same directory.
Now I don't want to give the url to the test.js file. I want the node.js file to also send the test.js file, so that it ends up in the same directory as index.html. And then index.html can load it from the same directory.
Is there a way I can specify in the node.js with code to also send the test.js file?
Thanks.
Are you familiar with Express, as dandavis mentioned? Express allows you to set a directory for your static files. See my standard config below:
app
.use('view engine', jade)
.use(express.compress())
.use(express.limit('10mb'))
.use(express.bodyParser())
.use(app.router)
.use(stylus.middleware({
src: __dirname + '/www',
compile: function(str, path) {
return stylus(str)
.set('filename', path)
.set('compress', false)
.set('warn', true);
}
}))
.use(express.static(__dirname + '/www'))
.use(express.logger());
The important part here is second from the bottom. Essentially, Express now knows to look for any assets you specify in your HTML within that static directory. For me, I create a folder titled WWW within my server folder, then add to it my JS, CSS, and images.
For example, say I create the "stylus" folder within my WWW folder, and add to it store.css. My link to that CSS asset would be the following in my Jade template:
link(rel="stylesheet", type="text/css", href="stylus/store.css")
Express knows to look for that asset relative to the __dirname + '/www' path, and thus locates the "stylus" folder and the CSS assets it contains. Hope this helps, and that I haven't ventured away from your intent!