Can't find Flask template specified by relative path - python

I am trying to render the index.html template in my Flask app's templates folder. However, I get a TemplateNotFound error. The template exists. How do I render it?
#app.route('/')
def index():
return render_template('../../templates/index.html')
Traceback (most recent call last):
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "G:\Projects\Intellij\Python\HelloPython\controller\web\WebHomeController.py", line 10, in webIndex
return render_template('../../templates/index.html', message=message)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\templating.py", line 133, in render_template
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\jinja2\environment.py", line 869, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\jinja2\environment.py", line 830, in get_template
return self._load_template(name, self.make_globals(globals))
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\jinja2\environment.py", line 804, in _load_template
template = self.loader.load(self, name, globals)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\jinja2\loaders.py", line 113, in load
source, filename, uptodate = self.get_source(environment, name)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\templating.py", line 57, in get_source
return self._get_source_fast(environment, template)
File "G:\Settings\Windows\ProgramFiles\Python\Python35-32\lib\site-packages\flask\templating.py", line 85, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: ../../templates/index.html

render_template takes the name to be looked up by the Jinja env, which has the templates folder it its lookup path. Only specify the path after that.
# index.html is in the templates folder
render_template('index.html')
# users/detail.html is in a sub-folder under templates
render_template('users/detail.html')

Related

Jinja2Exception Flask template not found

I am getting the error jinja2.exceptions.TemplateNotFound. Even I have my HTML files in the templates folder, still I am receiving this error. It was working fine sometime ago, and now I am getting this error.
Full error code:
Traceback (most recent call last)
File "E:\price\web\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "E:\price\web\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "E:\price\web\Lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "E:\price\web\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "E:\price\web\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "E:\price\web\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "E:\price\web\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "E:\price\web\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "E:\price\web\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "E:\price\web\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "E:\price\web\flasktest.py", line 6, in index
return render_template('about.html')
File "E:\price\web\Lib\site-packages\flask\templating.py", line 138, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 1068, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 997, in get_template
return self._load_template(name, globals)
File "E:\price\web\Lib\site-packages\jinja2\environment.py", line 958, in _load_template
template = self.loader.load(self, name, self.make_globals(globals))
File "E:\price\web\Lib\site-packages\jinja2\loaders.py", line 125, in load
source, filename, uptodate = self.get_source(environment, name)
File "E:\price\web\Lib\site-packages\flask\templating.py", line 60, in get_source
return self._get_source_fast(environment, template)
File "E:\price\web\Lib\site-packages\flask\templating.py", line 89, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: about.html
Here's my code snippet:
from flask import Flask, render_template
app = Flask('test', template_folder= 'templates')
#app.route('/')
def index():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug = True, host = '127.0.0.1', port = 5000)
Here is the screenshot of my directories:
Update:
My code is working perfectly in a new file. Is it due to cache?
Tried app = Flask(name) but still same issue.
A new Test.py file works completely fine but not the old ones.
have a look at this topic https://flask.palletsprojects.com/en/2.0.x/api/#application-object and head over this section About the First Parameter
so my guess, you should import the right package name,
so try __name__ instead of test
app = Flask(__name__, template_folder='templates')
BTW, Flask already expects templates as default folder to look at, meaning it's optional and you can define your app like so
app = Flask(__name__)
Flask looks for templates by default in the "templates" folder https://flask.palletsprojects.com/en/2.0.x/quickstart/#rendering-templates.
Try this:
app = Flask(__name__)
#app.route('/')
def index():
return render_template('about.html')
Finally I got the solution where it went wrong.
I was doing this:
app = Flask('__name__')
But the correct way was this:
app = Flask(__name__)

How would i fix this error in python WTForms?

I have attempted to make a Full-Feature Web App, and this includes using WTForms as the databasing resource, I am stumped at this error,
jinja2.exceptions.UndefinedError: 'wtforms.fields.core.StringField object' has no attribute 'username'
Traceback (most recent call last):
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 2328, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 2314, in wsgi_app
response = self.handle_exception(e)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 1760, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise
raise value
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 2311, in wsgi_app
response = self.full_dispatch_request()
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 1834, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 1737, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise
raise value
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 1832, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/app.py", line 1818, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/lkendon/flaskblog/flaskblog.py", line 36, in register
return render_template('register.html', title='Register', form=form)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/templating.py", line 135, in render_template
context, ctx.app)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/flask/templating.py", line 117, in _render
rv = template.render(context)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/jinja2/asyncsupport.py", line 76, in render
return original_render(self, *args, **kwargs)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/jinja2/environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/jinja2/environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/lkendon/flaskblog/venv/lib/python3.7/site-packages/jinja2/_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "/Users/lkendon/flaskblog/templates/register.html", line 1, in top-level template code
{% extends "layout.html" %}
File "/Users/lkendon/flaskblog/templates/layout.html", line 41, in top-level template code
{% block content %}{% endblock %}
File "/Users/lkendon/flaskblog/templates/register.html", line 10, in block "content"
{{form.username.username(class="form-control form-control-lg")}}
jinja2.exceptions.UndefinedError: 'wtforms.fields.core.StringField object' has no attribute 'username'
What on earth is the issue here, I was following a tutorial and i have the same details inputted through the provided snippets.
Looking at the traceback, you're calling {{form.username.username(... which should be {{form.username(...

Flask Pdfkit create pdf from template and save it

I use pdfkit to create an invoice pdf. At the moment I just want to save it. Later I will save the invoice filename in the DB and store in on AWS3.
But for now I get an IO Error when trying to save the file, probably because I request it the wrong way:
pdfkit.from_file(render_template('invoice_template.html', invoice_id=1, invioce_date_start=str(date.today()),
invioce_date_end=str(date.today()), invioce_company_name=form.zahlung_firma.data, invioce_user_vorename=form.vorname.data,
invioce_user_surname=form.nachname.data, invioce_user_email=current_user.email), str(current_user.id) + '-invoice.pdf')
The Error:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Python27\lib\site-packages\flask_login.py", line 758, in decorated_view
return func(*args, **kwargs)
File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\main.py", line 114, in decorated_function
return func(*args, **kwargs)
File "C:\Users\User\Eclipse-Workspace\Monteurzimmer\main.py", line 1252, in logged_in
invioce_user_surname=form.nachname.data, invioce_user_email=current_user.email), str(current_user.id) + '-invoice.pdf')
File "C:\Python27\lib\site-packages\pdfkit\api.py", line 47, in from_file
configuration=configuration, cover_first=cover_first)
File "C:\Python27\lib\site-packages\pdfkit\pdfkit.py", line 41, in __init__
self.source = Source(url_or_file, type_)
File "C:\Python27\lib\site-packages\pdfkit\source.py", line 12, in __init__
self.checkFiles()
File "C:\Python27\lib\site-packages\pdfkit\source.py", line 32, in checkFiles
raise IOError('No such file: %s' % self.source)
IOError: No such file: <!doctype html>
The template itself can be found here, I just edited the jinja variables:
pdfkit.from_file() expects a file object as its input, but render_template() returns a string. Try pdfkit.from_string() instead.
More information: pypi - pdfkit

Flask with Jinja2 throws AttributeError: 'TemplateData' object has no attribute 'data'

I am trying to render a simple Jinja template. No matter what the template is, or what variables are passed to it, I get an error when trying to render. Why am I getting this error and how do I fix it?
frontend = Blueprint('frontend', __name__, template_folder='templates')
#frontend.route('/')
def index():
stuff = dict()
stuff['page_title'] = 'Something'
stuff['center_piece'] = 'Random'
return render_template('base.html', stuff=stuff)
Basic template, without variables, still causes error.
<html>
<head>
<title>Something</title>
</head>
<body>Something else</body>
</html>
File "/env/lib/python3.4/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/env/lib/python3.4/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/env/lib/python3.4/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/env/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/env/lib/python3.4/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/env/lib/python3.4/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/env/lib/python3.4/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/env/lib/python3.4/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/env/lib/python3.4/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/env/lib/python3.4/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/app/frontend/controller.py", line 12, in index
return render_template('base.html', stuff=stuff)
File "/env/lib/python3.4/site-packages/flask/templating.py", line 127, in render_template
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "/env/lib/python3.4/site-packages/jinja2/environment.py", line 851, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "/env/lib/python3.4/site-packages/jinja2/environment.py", line 812, in get_template
return self._load_template(name, self.make_globals(globals))
File "/env/lib/python3.4/site-packages/jinja2/environment.py", line 786, in _load_template
template = self.loader.load(self, name, globals)
File "/env/lib/python3.4/site-packages/jinja2/loaders.py", line 125, in load
code = environment.compile(source, name, filename)
File "/env/lib/python3.4/site-packages/jinja2/environment.py", line 555, in compile
defer_init=defer_init)
File "/env/lib/python3.4/site-packages/jinja2/environment.py", line 515, in _generate
return generate(source, self, name, filename, defer_init=defer_init)
File "/env/lib/python3.4/site-packages/jinja2/compiler.py", line 62, in generate
generator.visit(node)
File "/env/lib/python3.4/site-packages/jinja2/visitor.py", line 38, in visit
return f(node, *args, **kwargs)
File "/env/lib/python3.4/site-packages/jinja2/compiler.py", line 816, in visit_Template
self.blockvisit(node.body, frame)
File "/env/lib/python3.4/site-packages/jinja2/compiler.py", line 492, in blockvisit
self.visit(node, frame)
File "/env/lib/python3.4/site-packages/jinja2/visitor.py", line 38, in visit
return f(node, *args, **kwargs)
File "/env/lib/python3.4/site-packages/jinja2/compiler.py", line 1250, in visit_Output
const = child.as_const(frame.eval_ctx)
File "/env/lib/python3.4/site-packages/jinja2/nodes.py", line 467, in as_const
return Markup(self.data)
AttributeError: 'TemplateData' object has no attribute 'data'
I got this error when I refactored a variable called data to data_repo in PyCharm and somehow changed my Jinja2 installation's "nodes.py" file as well. This is the function that throws the error:
class TemplateData(Literal):
"""A constant template string."""
fields = ('data',)
def as_const(self, eval_ctx=None):
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
if eval_ctx.autoescape:
return Markup(self.data)
return self.data
My refactor changed the string in the fields tuple but not the return value, leading to an AttributeError with any template.

jinja2.exceptions.TemplateNotFound error [duplicate]

This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(14 answers)
Closed 7 years ago.
i use flask and i got this error when i call this url: /login
Here's my login method:
#app.route('/login')
def login():
if authenticateForPanel():
return redirect(url_for("panel"))
else:
getParam = request.args.getlist('redirect_uri')
if getParam:
ref =getParam[0]
else:
ref="/panel"
return render_template( themesDir + g.blogOptions['active_theme']+'/login.html', blogOptions = g.blogOptions, ref=ref )
And the traceback:
Traceback (most recent call last):
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/ozcan/Documents/python/app.py", line 209, in login
return render_template( themesDir + g.blogOptions['active_theme']+'/login.html', blogOptions = g.blogOptions, ref=ref )
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/templating.py", line 124, in render_template
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/jinja2/environment.py", line 758, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/jinja2/environment.py", line 719, in get_template
return self._load_template(name, self.make_globals(globals))
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/jinja2/environment.py", line 693, in _load_template
template = self.loader.load(self, name, globals)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/jinja2/loaders.py", line 115, in load
source, filename, uptodate = self.get_source(environment, name)
File "/Users/ozcan/Library/Python/2.7/lib/python/site-packages/flask/templating.py", line 61, in get_source
raise TemplateNotFound(template)
TemplateNotFound: static/themes/default/login.html
I am absolutely sure the login.html is there(static/themes/default/404.html).Why can this occur?
You put your template in the wrong place. From the Flask docs:
Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package:
See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates
I think you shouldn't prepend themesDir. You only pass the filename of the template to flask, it will then look in a folder called templates relative to your python file.

Categories

Resources