Django: Passing a static html file into view produce TemplateDoesNotExist error - python

I have a django app and a view for the home page where I want to use a static html file for the homepage. My file structure is like this:
project/
stats (this is my app)/
urls.py
views.py
stats.html
(other files here)
In my views.py I have the following code:
from django.shortcuts import render_to_response
def index(request):
return render_to_response('stats.html')
When I run the urls, I just have the index page. I go to the stats page and I receive a TemplateDoesNotExist Error. Looking for an answer I tried to put stats/stats.html instead for the path, but I still get the same error. What is the correct way of doing this?

In your project directory, add a directory called 'templates' and inside the templates directory, create 'stats' directory. Put your HTML file in the stats directory.
Then change your settings file at the bottom from
TEMPLATE_DIRS = (
    os.path.join(SETTINGS_PATH, 'templates'),
)
To
TEMPLATE_DIRS = (
    os.path.join(BASE_PATH, 'templates'),
)

You can arrange your project like this
project/
stats (this is my app)/
urls.py
views.py
stats.html
templates/
stats/
stats.html
In your views.py, write this:
def index(request):
return render_to_response('stats/stats.html')
make sure there is 'stats' in the INSTALLED_APPS list in the settings.py.

Related

Django templates rendering issue

I'm new to Django, trying my hand at creating a web app based on the self learn tutorial. i have created a app with name "travello" and project name is "travellproject", in the views i'am trying to render a html page.
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def homepage(request):
return render(request,'homepage.html')
i have created the "templates" directory under travellproj (please refer the directory structure below) also defined DIRS of template variable as below and urls.py as below.
"DIRS": [os.path.join(BASE_DIR,'templates')],
urlpatterns = [
path("",views.homepage),
path("admin/", admin.site.urls),
]
But I'm receiving a TemplateDoesNotExist error, please help.
Error
TemplateDoesNotExist at /
homepage.html
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 4.1.5
Exception Type: TemplateDoesNotExist
Exception Value:
homepage.html
Exception Location: C:\Users\Django\first_proj\lib\site-packages\django\template\loader.py, line 19, in get_template
Raised during: travello.views.homepage
Directory structure:
travello
|-views.py
travellProj
|-templates -- > homepage.html
|-urls.py
|-setting.py
Your templates folder should be at the root of your site. Let see how it should look like:
Project_folder
|-travelproj <-- Your site configuration folder
|-|-urls.py
|-|-wsgi.py
|-|-asgi.py
|-|-.......
|-travello <-- this is an application
|-|-views.py
|-|-urls.py
|-|-templates <-- templates for this app only
|-|-|-travello
|-|-|-|-template1.html
|-|-|-|-.......
|-|-.......
|-templates <- This is the templates folder for your site
|-|-homepage.html
|-|-..........
|-manage.py
|-requirements.txt
So in your case your templates folder is in your site configuration folder which is not a good practice. you have to move it one step higher.
Good practices tips:
At the root of your site (same level than manage.py) you have a templates folder which will contain the templates commons to all your applications.
In each application you have a folder templates/app_name which contain all the templates specifics for this application.
You have the same architecture for statics.
Inside templates create another new directory by your app name travello then keep the html file inside the travello directory
travello
| templates/travello/homepage.html
|-views.py
travellProj
|-urls.py
|-setting.py
Then views should be like
def homepage(request):
return render(request,'travello/homepage.html')

Unable to find flask template [duplicate]

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.

Can't render html page on the templates folder in the django project?

Code of the views file
Template doesn't exist error is revoking. Firstly django-project is reading html file as django template file but I added "emmet.includeLanguages": {"django-html": "html"}, to settings.json but it doesn't help
Try to create or edit your template name to index.htm, then try:
def home(request) :
.... code here....
return render(request, 'index.html')
Let me know if you get an error.

where to put django-registration's activation_email.txt template

As per the docs,it expects this file in a folder named 'registration' in templates directory.I tried that ,but I am getting a templateNotFound exception.
I have configured the registration template location like
from django.conf.urls.defaults import *
urlpatterns=patterns('django.contrib.auth.views',....)
urlpatterns+=patterns('registration.views',
url(r'^register/$','register',{'template_name':'myapp/registration_form.html'},name='myapp_register'),
)
Is there some place I can configure the location for activation_email.txt template ? When I submit the registration form ,the user is created in db ,but django searches all over python path for the activation_email.txt template
Why is it that all other templates are found with out any problem while this template is not found?
Look at your TEMPLATE_DIRECTORIES setting. The template paths are relative to any of the TEMPLATE_DIRECTORIES.
If template_name is myapp/registration_form.html, then you should create a dir "myapp" in one of the TEMPLATE_DIRECTORIES, and put registration_form.html in there.
To double check TEMPLATE_DIRECTORIES, run manage.py shell and in there from django.conf import settings; print settings.TEMPLATE_DIRECTORIES.

What may be the problem (Django views)...?

I am writing a GUI application using Django 1.1.1.
This is the views.py:
from django.http import HttpResponse
def mainpage(request):
f=open('pages/index.html','r').readlines()
out=''''''
for line in file:
out+=line
print out
return HttpResponse(out)
I am trying to load the contents of index.html which is inside a folder pages inside the GUI application folder.
My project's urls.py is
from django.conf.urls.defaults import *
from gui.views import *
urlpatterns = patterns('',
(r'^/$', mainpage)
)
When I run the server I get a 404 error for the root site.
How can I load the index.html file through views?
If you require just simple output of html page, this can be achieved by simply putting following into urls.py:
(r'^$', 'direct_to_template', {'template': 'index.html'})
For the root page don't use r'^/$', just r'^$', because this ^ means "start of the string after domain AND SLASH" (after 127.0.0.1/ if you run app on localhost). That's why localhost:8080// works for you.
Edit: check yours paths too. Do you have 'pages' directory in the same directory that views.py is?
Anyway: it seems that you are trying to do something bad and against Django architecture. Look here for tutorial on writing your first application in Django.
Your actual code in the view is incorrect. Here is my fixed up version:
from django.http import HttpResponse
def mainpage(request):
lines=open('loader/pages/index.html','r').readlines()
out=''''''
for line in lines:
out+=line
print out
return HttpResponse(out)
Note that in your code the line that reads from the file is:
f=open('pages/index.html','r').readlines()
You open the file and read the lines into f and then try to iterate over lines. The other change is just to get my path to the actual index file right.
You might want to read this http://docs.djangoproject.com/en/dev/howto/static-files/ if you want to serve static pages.
Got it! ;)
It seems that the mainpage function actually runs on the urls.py (as it is imported from the views.py) file so the path I must provide is gui/pages/index.html. I still had a problem, 'type object not iterable', but the following worked:
def mainpage(request):
f=open('gui/pages/index.html','r').readlines()
return HttpResponse(f)
And url pattern was r'^$' so it worked on http://localhost:8080/ itself.

Categories