Dynamic TEMPLATE_DIRS - python

I want to be able to have dynamic directories where templates will reside. Let me explain what I mean. I have an application system wich has such a file structure:
\proj
__init__.py
settings.py
urls.py
...
\system
__init__.py
models.py
views.py
urls.py
\modules
\module_1
__init__.py
models.py
views.py
urls.py
\templates ## Attention
one.html
two.html
\module_2
__init__.py
modules.py
\templates ##
three.html
four.html
...
\module_N
...
As you can see there is a modules folder, which contains "atomic" modules, atomic in a sense that they have all necessary files, including templates in one place. So that module_1 has a template folder with its tempaltes, module_2 has a templates folder and all other modules have their own templates folder. What I want is to be able to refer to these templates folders in my settings.py file, so that when I upload a brand new module to modules folder, I would not have to change this settings.py file. So my question is, how can I dynamically build TEMPLATE_DIRS variable:
TEMPLATE_DIRS = (
## how to implement this???
)
EDIT
I'm considering another approach. First, to convert my modules to dinamic applications like this:
MODULES_DIR = 'system/modules'
for item in os.listdir(MODULES_DIR):
if os.path.isdir(os.path.join(MODULES_DIR, item)):
app_name = 'system.modules.%s' % item
INSTALLED_APPS += (app_name, )
And then to do something to make Django look for templates in all applications' folders. But I'm not sure whether it will work and how can I complete this task.

This is simply app-specific templates, which is already catered for by the APP_DIRS flag in the template settings dict. There shouldn't be any other configuration needed.

Related

show dinamic data on my website by flask [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.

Get the path of "static" folder in django automatically

I am developing Django (1.6) app. In my app I have to use the static images to be displayed on the HTML pages (like magnifying glass for search box,logo,etc). After little bit of research I came to know that we have to create a folder (say "static") which holds the static images and then I have mention the path in my settings.py like shown below :
`STATIC_URL = '/static/'
STATICFILES_DIRS = (
"C:/Users/Welcome/Desktop/business/static/polls",
"C:/Users/Welcome/Desktop/business/static",
)`
I also added the code shown below in urls.py too after which I could get the images on my HTML pages.
urlpatterns = patterns(''......... ...........) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
My question now is every time I change the directory (current working directory or if I transfer the project to another pc ) I have to update the path in settings.py.
How to not do that ? how to get path of "static" folder automatically when I run my project. Please do help. What I'm missing ?
Normally the static files finder of django will expect that your app itself has a static sub-directory, and you can store everything there.
+ myproj
- manage.py
+ app
- __init__.py
- settings.py
- urls.py
+ static <-- notice the static directory.
+ templates
This is good of course for development where the Django server is the one serving these static files. In production you'll need to collect everything to the location declared in your STATIC_ROOT setting with the collectstatic management command.
This way you won't need to change the location each time you copy your project to a new location or a new computer.
Of course, that once you do that you can drop the STATICFILES_DIRS definition from your settings.py. This setting is used to tell Django that there are other static assets that reside outside of a certain app. If you want to use it anyway then you can define those directories relative to the project itself, i.e.:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static")
)
Your urls.py should then use the staticfiles_urlpatterns like this:
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
For more information see the Django documentation on static files:
https://docs.djangoproject.com/en/1.7/howto/static-files/
I just figured out the solution for my question. First you need to get the current working directory and then for looking out for the folder in that current working directory(where your project is being installed) assign this to variable say path_for_images and then pass it to the STATICFILES_DIR as shown below:
path_for_images = os.getcwd()+"\static"
STATICFILES_DIRS = ( path_for images,) <-- note ,(comma) after `path_for_images`
No need to do any changes for the urls.py and images get loaded. This isn't exact pythonic way but it's surely one of the way.

How do you extend a Django project root HTML file in project apps?

Below is the structure of my Django App:
Project/
static/
App1/
App2/
App3/
...
So I have a Django project, and I want to keep the HTML/CSS styling uniform across the apps in the project.
How does one go about extending a HTML template residing in the Project folder from each of these apps?
I have only been successful extending HTML templates within App folders for each respective App.
My project settings has static files set to be located in "/static/"
You can put your project-common templates in Project/templates and add the /path/to/Project/templates to your TEMPLATE_DIRS setting in your settings.py file. prepend the root to everything else, so it gets searched first:
TEMPLATE_DIRS = (
# Don't forget to use absolute paths, not relative paths.
"/path/to/Projects/templates",
#other dirs ...
)
Then you go extend it from your application templates as usual:
{# App1/templates/App1/template1.html #}
{% extends "template_in_project_root.html" %}
...
the TEMPLATE_DIRS setting

Django path to templates for apps

Let's assume I have the following project:
myproject/
myproject/
__init__.py
settings.py
urls.py
wsgi.py
templates/
base.html
app1/
__init__.py
admin.py
models.py
urls.py
views.py
templates/
base.html
index.html
I want to have a base template, which all other apps will use, in myproject/template/base.html.
Then, I want to have the app templates in app/templates.
One option would be writting in myproject/settings.py:
TEMPLATE_DIRS = (
"/dir/to/myproject/myproject/templates",
"/dir/to/myproject/app1/templates",
)
But, is this the best way to do it?
Django supports this automatically, via the app_directories loader that is installed by default. See the documentation.
Maybe you can do the following:
#settings.py
import os
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH, 'templates'),
os.path.join(PROJECT_PATH, 'app1/templates'),
)
This will save you from editing each and every absolute path in setting file in case you happen to move your project.

No Module named Contact Error-Chapter 7 Exercise in Django Book

I've received the following error when trying to set up a contact subdirectory inside the mysite directory.
Here is how I structured the urls.py script:
from mysite.contact import views as contact_views
(r'^contact/$', contact_views.contact),
Do I need to change anything in the settings.py TEMPLATE_DIRS, so, I can call the contact_form.html template correctly?
Yes, template_dirs needs to contain the path to the templates folder.

Categories

Resources