This question was answered more or less here but it didn't work to me and as far I can see more people have the same problem.
In my settings.py I have this lines:
#TEMPLATE_DIRS = [os.path.join(BASE_DIR,'..', 'templates'),]
TEMPLATE_DIRS = ("/root/GODJANGO/thedjango/django_project",)
The comented line didn't work. It works if I write the full path but It's not professional and I don't wanna have problems when I three months later I migrate my server because I will not remember this thing.
Can anybody tell me how to write My Path correctly ("dynamically, I mean")
Please tell me where is the best directory to put my templates folder and also my admin templates folder
If you have the following project layout:
manage.py
myproject/
settings.py
urls.py
wsgi.py
templates/
admin/
app1/
app2/
Then you can dynamically set your template directory by putting the following in your settings.py:
...
SETTINGS_PATH = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, "templates")
)
...
if your template folder is in the parent folder to the settings.py you will need something like:
...
SETTINGS_PATH = os.path.abspath(os.path.dirname(__file__))
PROJECT_FOLDER = (os.path.split(SETTINGS_PATH))[0] # get the parent directory
TEMPLATE_DIRS = (
os.path.join(PROJECT_FOLDER, "templates")
)
...
As you can see, we are manually traversing the file tree to find where the templates folder is and assigning it dynamically.
The best place for your templates folder depends on your project layout (< 1.4 or >= 1.4) but it would be probably safest to say that it should be alongside your settings.py file. Your admin template folder will go inside your base templates folder: templates/admin/.
What are you trying to do with this paramater ".." in the commented line?
if it is means parent directory you can use os.path.dirname(BASE_DIR)
Second part:
It depends you or team work with; i love to keep templates directory in every app's directory (and if you do like this you don't need to define TEMPLATE_DIRS). I mean if i have templates of news app, they goes ../news/templates/. But this time my friend (front-end developer) says i cant find them, can we put all of them in one place?
so i put them in one directory with sub directories (../templates/news/). This main templates directory is in main project directory (near the manage.py file). And if you add this main directory to INSTALLED_APPS (because its kind an app) you don't need to define TEMPLATE_DIRS too. And even you can create models.py admin.py files here.
Considering the second part of your question and according to this the safest part for your templates is to create a templates dir under your projects main directory (e.g. blog).
As for the first part i am not sure.
Related
I guess this is a question related to best practises in Django development.
I'm trying to build a web service with a main page (base.html) that contains multiple apps. I would like to make the apps self-contained, so I've made a templates directory in each app, and would also like to take advantage of the template inheritance feature of Django to make this whole thing as fluid as possible.
Now my concern is, where should I put the base.html in my project, so that the system knew where to find it?
Also, what changes should I make in the settings.py file in order for the system to be able to connect the templates? Is there a standard or a known method that takes minimal effort for this sort of arrangement?
You can put the templates folder in the project folder (ie folder contains settings.py).
as #danialroseman said, you just need to update the DIRS in TEMPLATES variable in settings.py. Let the project folder be myproject(ie folder contains settings.py)::
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
### ADD YOUR DIRECTORY HERE LIKE SO:
'DIRS': [ os.path.join(BASE_DIR,'myproject', 'templates')],
...
you dont need to create a seperate app.
One common design pattern that I have both seen and used is to have a centralized "app" as a part of your project that contains all the shared "stuff" you care to use in other applications. So you might have the following directory structure:
base/
static/
css/
common.css
js/
common.js
templates/
base.html
myapp1/
urls.py
views.py
templates/
...
myapp2/
urls.py
views.py
templates/
...
myproject/
settings.py
urls.py
Now you just include the "base" application just like any other, and you put shared stuff inside it. Other applications can refer to templates that live there, and can include any common libraries that you may want to share.
In settings.py:
INSTALLED_APPS = ['base', 'myapp1', 'myapp2']
There's no need for a central app for this. The TEMPLATES setting also includes an option for DIRS, which is a list of directories that will always be searched. So you can set this to an appropriate directory - eg os.path.join(BASE_DIR, 'templates') and put your non-app-specific templates such as base.html there.
I have finished reading the Django official tutorial which teaches how to create a simple polls app, which is the way they chose to teach beginners the Django basics.
My question is, now that I know how to make a simple app and want to create my own website (using Django), should the main (front) page of my website, be an app as well? If so, how do people usually call it and configure it? I mean, it should do nothing but render a html template, so why make it so complicated? If not, where do I put all the static files and how do I reference them? I am a bit confused and could use your help. Maybe I misunderstood Django's main use?
You can create your templates and static files in the root project folder where your manage.py file lives. In the root folder create the following folders:
templates (for HTML)
static (for CSS, JS and images)
In your settings.py file, make these variables look like this:
TEMPLATES = [
{
...
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
...
},
]
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
Note: STATICFILES_DIRS variable is initially not present in the settings.py file, but you can add that by your own. Django, by default, finds static files in the static directory of each app. If you want Django to read the static directory you created in the project root, you need to add this variable. Django official documentation reference: https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-STATICFILES_DIRS
To render these templates you can create views.py in the directory where your settings.py file lives and add the route in urls.py in the same folder.
This is one of the several ways to achieve what you want. Hope you won't need to plug these templates (eg, your home page) to or say use these templates in any other project, otherwise do as Timmy suggested in the comment on your post.
I usually start with 3 apps (call them whatever you want):
layout - basic layout: some common static files and a basic-template (other templates extend this one, main purpose is to
include a common html <head> ). Also contains the home-page and some other simple pages.
config - contains the project settings / configuration, and the main urls.py (and in my case also wsgi.py)
myapp - the actual app I want to create.
This nicely separates functionalities. Often I can just re-use the base app for other projects.
$ ./manage.py startproject config
$ ./manage.py startapp layout
$ ./manage.py startapp myapp
My setup
settings.py
INSTALLED_APPS = (
...
'myprojectname',
...
)
STATIC_ROOT = '/var/www/a_valid_path/'
LOCALE_PATHS = (
os.path.join(BASE_DIR, "locale"),
)
urls.py
js_info_dict = {
'domain': 'djangojs',
'packages': ('myprojectname',),
}
urlpatterns = patterns('',
...
url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
...
)
My project structure is as follows:
|- projectname
|--- app1
|--- app2
|--- manage.py
|- virtualenv
|- static
|--- js
|--- css
I also have the locale folder in the root folder of my project, where manage.py is located.
What I'm doing
Simply running:
./manage.py -l ro -d djangojs
My problem
It's not working. No .po file is being generated. Server-side translation works, however (views + templates). I've followed all advice, and still nothing. Even tried to create the djangojs.po file myself to see if Django deletes it, or does something with it -- nope.
No error is generated, just processing locale ro is shown (for a really short time -- too short if you ask me), and that's that. Any help?
Edit: Forgot to mention that my folder containing the JS files is not inside each Django app, but in a separate location. Still, shouldn't Django look inside the STATICFILES_DIRS?
Django's makemessages only will make messages from files that are in on one of your TEMPLATE_DIRS. So any files you want to translate need to be in one of those directories.
You can do that in one several ways:
Place the *.js files in one of your TEMPLATE_DIRS as is
In-lining your JS in the html files
Place all the strings that need translation in data-attributes on the dom and grab them from the dom via JS
Are you running makemessages from a directory parent of the ones containing your JavaScript files?
Do your JavaScript file names ends with a .js?
Do you either use django.gettext('string') or _('string') to mark strings requiring translations?
I've experienced the same issue. I've discovered that the issue is reported in the Django ticket #23717: https://code.djangoproject.com/ticket/23717
Fixes are in upcoming stable 1.7.2 version: https://docs.djangoproject.com/en/1.7/releases/1.7.2/
I've installed 1.7.2 and confirmed that the issue is fixed.
I had the same problem when using the Django i18n, after many times trying, I finally got the correct answer: we need to put the .js files into the project directory, which was specified when we assign 'js_info_dict'.
But usually we put the JavaScript files in the same level catalog as project, so there is the problem. (we don't need to put the JavaScript files into templates directory).
The template file is saved under the app directory, but it raises TemplateDoesNotExist exception while rendering:
Template-loader postmortem as following:
Django tried loading these templates, in this order:
Using loader django.template.loaders.app_directories.Loader:
...
$PROJECT/apps/myapp/templates/search.html (File does not exist)
...
I'm wondering why it looks for:
$PROJECT/apps/myapp/templates/search.html
rather than:
$PROJECT/apps/myapp/templates/myapp/search.html
The latter does exist indeed
$PROJECT/apps/myapp/templates/search.html. That is the path it'll look for as the doc says.
django.template.loaders.app_directories.Loader will look for a templates directory inside all the INSTALLED_APPS in order.
django.template.loaders.filesystem.load_template_source: This loader loads templates from the filesystem, according to TEMPLATE_DIRS. It is enabled by default.
django.template.loaders.app_directories.load_template_source: This loader loads templates from Django applications on the filesystem. For each application in INSTALLED_APPS, the loader looks for a templates subdirectory. If the directory exists, Django looks for templates there.
This means you can store templates with your individual applications, making it easy to distribute Django applications with default templates. For example, if INSTALLED_APPS contains ('myproject.polls', 'myproject.music'), then get_template('foo.html') will look for templates in this order:
/path/to/myproject/polls/templates/foo.html
/path/to/myproject/music/templates/foo.html
Note that the loader performs an optimization when it is first imported: it caches a list of which INSTALLED_APPS packages have a templates subdirectory.
This loader is enabled by default.
Supposing that you have a default project and app created as
django-admin startproject xyz
django-admin startapp abc
both xyz and abc folders are in main project folder
Following minimal changes are required to get first template working
in settings.py change INSTALLED_APPS to add 'abc' (I forgot and failed)
in urls.py add
add line: import abc.views
change urlpatterns to add path('abc/', abc.views.index)
in index definition of views.py use loader.get_template('abc/index.html')
Create abc/templates/abc/index.html file ( I wrote "template" and spent few hours before I realized that is was "templates")
make sure the templates and inside folders have execute permission and html file have read permission for "other" users. (I worked as root and failed due to this error)
Restart the project (runserver or apache2 service)
Summary of my mistakes
Edit INSTALLED_APPS
"templates" is default
setup x and r permissions
Ensure your app is added to settings.py INSTALLED_APPS
Ensure your config in apps.py has a name equal to the name of the application directory.
class DemoConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'app' # this must be the same as the parent directory
Add them to your settings file.
import os
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, "/apps/myapp/templates/"),
)
I have a Django 1.3 project with this options in settings.py
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
TEMPLATE_DIRS = (
os.path.join(SITE_ROOT, 'templates'), )
But in Django 1.4 by default settings.py is moved in subdirectory with name that is equal to project name. Because of that static, media and templates directories now have to be moved in the same subdirectory?
Is this what I have to do, or just change STATIC_ROOT, MEDIA_ROOT and TEMPLATE_DIRS options?
I know that both variants are OK, but what is best practice for this in Django 1.4?
And also I know that every app can have it's own templates and static directories.
And is it better to put all other application directories inside the same subdirectory? This is not what is happening by default using manage.py startapp
OK the scheme that I follow is this:
myproject/requirements.txt - pip installable packages
myproject/deployment - Deployment stuff like server config files, fixtures(dummy data), etc.
myproject/docs - project's docs
myproject/tests - project's tests
myproject/myproject - project's operational code(and settings.py, urls.py)
Expanding myproject/myproject folder:
myproject/myproject/app1 - a regular app(encompassing its specific templates/static files)
myproject/myproject/app2 - another regular app(same as above)
myproject/myproject/website - semi special app, by convention.
This website app houses basically 4 things:
1) an empty models.py(so that django will consider it as a valid app)
2) a views.py with the entry point index view. Maybe some other views that don't fit in any other specific app.
3) a management dir with custom django commands which apply to the whole project.
4) a templates dir that has the 404.html and 505.html. Also it has a subdir called website that includes universal/base html templates that every other app extends, plus
the index.html.
5) a static dir with subsequent subdirs named css, js and media for global static files.
Nothing exotic I guess. I think that most people follow a similar pattern, but I would like to here any inefficiencies with this, if any.
EDIT:
with regards to settings for production VS development I use
the popular settings_local pattern, which you can read here and eventually will
lead you here, which describes a better pattern.