Django templates and unipath - python

I'm trying to use unipath module in my django project as it mentioned in Two Scoops of Django book and something works not as intended.
In my settings.py I have this:
from unipath import Path
BASE_DIR = Path(__file__).ancestor(2)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [(BASE_DIR.child('templates'),)],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_ROOT = BASE_DIR.child('static')
MEDIA_ROOT = BASE_DIR.child('media')
And with that settings I'm getting TemplateDoesNotExist exception:
Using loader django.template.loaders.filesystem.Loader:
/var/www/(Path('/home/user/my_project/project/templates'),)/myapp/index.html (File does not exist)
What am I doing wrong?

Finally solved this problem!
Need to edit TEMPLATES' 'DIRS' string in settings.py to:
'DIRS': (BASE_DIR.child('templates'),),

Related

Error loading admin page after upgrading to django-1.11

So previously, I was using django-1.8 version & I am in the process of upgrading to django-1.11. When I load my /admin page, I get
Exception Type: TemplateDoesNotExist
Exception Value: admin/index.html
I have tried multiple options and dont know why django is not loading admin templates for django-1.11.
Few more details:
- I use django-jet for the admin interface
- My TEMPLATES in settings looks like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'custom_dir_1'),
os.path.join(BASE_DIR, 'custom_dir_2'),
os.path.join(BASE_DIR, 'custom_dir_3')
],
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.request',
'django.template.context_processors.i18n',
'django.contrib.messages.context_processors.messages',
'context_processors.base_context',
],
}
}
]
Let me know if I can provide any other information to debug better. Any guidance in this issue is super appreciated, Have been at this issue for 3rd consecutive day :-(
You must set APP_DIRS to True, i.e.:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [
...

Django Developments Template_DIRS setting failed

I was recently trying to learn Django for one of my private project.
When came to the Chapter on Template,the Django Book recommended setting template path in settings.py using the the following snippet
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__),'templates').replace('\\','/'),)
However ,when I opened the file setting.py I found nothing like "TEMPLATE_DIR" but a list:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
the the value related to the key "DIR",was a empty list. So I try to filled it with the content shown above.
And then, code something in the views.py(all the import was done )
def current_datetime(request):
now = datetime.datetime.now()
t = get_template("current_datetime.html")
html = t.render(Context({"current_date" : now}))
return HttpResponse(html)
And then mkdir templates in the same folder with setting.py , saved current_datetime.html in folder templates
Finally,run the project.and got the message in my terminal:
WARNINGS:
?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 > and the TEMPLATES dictionary takes precedence. You must put the values of the > following settings into your default TEMPLATES dict: TEMPLATE_DIRS.
System check identified 1 issue (0 silenced).
June 15, 2017 - 15:32:49
Django version 1.11.2, using settings 'mysite.settings'
Starting development server at 127.0.0.1:8000/
Quit the server with CONTROL-C.
When opened the address (127.0.0.1:8000/time/) in my Safari,here came the
error message:
enter image description here
Anyone help,please ??
There is a warning on TEMPLATE_DIRS, for that just be sure you don't have TEMPLATE_DIRS variable in your settings.py and restart development server.
Then for the error, you are actually using a Context object instead of a dict, you should render the template using a useful shortcut https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#example
from django.shortcuts import render
def current_datetime(request):
now = datetime.datetime.now()
return render(request, "current_datetime.html", {
'current_date' : now,
})
I think you have BASE_DIR in settings.py for define location so use like below
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
DIRS should be like below
'DIRS': [os.path.join(BASE_DIR, 'templates'),],

Add templates folder in Django 1.8

I have some problem adding the templates directory for my django project. My goal is to override the /django/contrib/admin/templates/registration/password_reset_form.html file.
My Django version is the 1.8. This is the templates part of my settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [PROJECT_PATH],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
In the templates folder inside my django project i add the modified password_reset_form.html.
My urls.py is like this:
url(r'^password/reset/$',auth_views.password_reset,name='password_reset'),
url(r'^password/reset/done/$',auth_views.password_reset_done,name='password_reset_done'),
url(r'^password/reset/complete/$',auth_views.password_reset_complete,name='password_reset_complete'),
url(r'^password/reset/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$',auth_views.password_reset_confirm,name='password_reset_confirm'),
I always do:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_PATH = os.path.join(BASE_DIR, 'templates')
print "Templates in: %s" %(PROJECT_PATH)
To make sure I have them in the right spot. What does that print? Also, post the output from find /path/to/templates where the path is the output from that print statement.
just copy the admin/templates/registration/password_reset_form.html to your templates folder and override it there. you dont need any change in settings

Templates problems in django

I wrote an app in django. And I want to write a index.html for it. But I can't make it run. I tried and inspect the settings and code but, it doesn't work either. I will paste the code. Hope someone can find the trick.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.core.context_processors.static',
],
},
},
]
I wrote a app named blog. I put the index.html in the ,blog/templates/blog/
views.py
def index(request):
posts = Post.objects.filter(published=True)
return render(request,'blog/index.html',{'posts':posts})
urls.py:
urlpatterns = [
url(r'^$', views.index, name='index')
]
I can't find any problems but it just does not work. It seems the template is not found but the config path is right. Or I missed something that I unaware of?
Add 'blog' to the INSTALLED_APPS tuple in settings.py
Also, below are the settings that work for me. Hope these will do the trick for you as well.
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_BASE_PATH = os.path.dirname(__file__)
PROJECT_DIR_NAME = os.path.split(PROJECT_BASE_PATH)[1]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(PROJECT_BASE_PATH, 'templates').replace('\\', '/')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)

What is the path that Django uses for locating and loading templates?

I'm following this tutorial on a Windows 7 environment.
My settings file has this definition:
TEMPLATE_DIRS = (
'C:/django-project/myapp/mytemplates/admin'
)
I got the base_template from the template admin/base_site.html from within the default Django admin template directory in the source code of Django itself (django/contrib/admin/templates) into an admin subdirectory of myapp directory as the tutorial instructed, but it doesn't seem to take affect for some reason.
Any clue of what might be the problem?
I know this isn't in the Django tutorial, and shame on them, but it's better to set up relative paths for your path variables. You can set it up like so:
import os.path
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
...
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media/')
TEMPLATE_DIRS = [
os.path.join(PROJECT_PATH, 'templates/'),
]
This way you can move your Django project and your path roots will update automatically. This is useful when you're setting up your production server.
Second, there's something suspect to your TEMPLATE_DIRS path. It should point to the root of your template directory. Also, it should also end in a trailing /.
I'm just going to guess here that the .../admin/ directory is not your template root. If you still want to write absolute paths you should take out the reference to the admin template directory.
TEMPLATE_DIRS = [
'C:/django-project/myapp/mytemplates/',
]
With that being said, the template loaders by default should be set up to recursively traverse into your app directories to locate template files.
TEMPLATE_LOADERS = [
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
]
You shouldn't need to copy over the admin templates unless if you specifically want to overwrite something.
You will have to run a syncdb if you haven't run it yet. You'll also need to statically server your media files if you're hosting django through runserver.
If using Django settings as installed, then why not just use its baked-in, predefined BASE_DIR and TEMPLATES? In the pip installed Django(v1.8), I get:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
### ADD YOUR DIRECTORY HERE LIKE SO:
BASE_DIR + '/templates/',
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Smart solution in Django 2.0.3 for keeping templates in project directory (/root/templates/app_name):
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMP_DIR = os.path.join(BASE_DIR, 'templates')
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMP_DIR],
...
in views.py just add such template path:
app_name/html_name
For Django 1.6.6:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = os.path.join(BASE_DIR, 'templates')
Also static and media for debug and production mode:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
if DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
else:
STATIC_ROOT = %REAL_PATH_TO_PRODUCTION_STATIC_FOLDER%
MEDIA_ROOT = %REAL_PATH_TO_PRODUCTION_MEDIA_FOLDER%
Into urls.py you must add:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from news.views import Index
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
...
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
In Django 1.8 you can set template paths, backend and other parameters for templates in one dictionary (settings.py):
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
path.join(BASE_DIR, 'templates')
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Official docs.
I also had issues with this part of the tutorial (used tutorial for version 1.7).
My mistake was that I only edited the 'Django administration' string, and did not pay enough attention to the manual.
This is the line from django/contrib/admin/templates/admin/base_site.html:
<h1 id="site-name">{{ site_header|default:_('Django administration') }}</h1>
But after some time and frustration it became clear that there was the 'site_header or default:_' statement, which should be removed. So after removing the statement (like the example in the manual everything worked like expected).
Example manual:
<h1 id="site-name">Polls Administration</h1>
Alright šŸ˜ Let's say you have a brand new project, if so you would go to settings.py file and search for TEMPLATES once you found it you just paste this line os.path.join(BASE_DIR, 'template') in 'DIRS' At the end, you should get somethings like this :
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'template')
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
If you want to know where your BASE_DIR directory is located type these 3 simple commands:
python3 manage.py shell
Once you're in the shell :
>>> from django.conf import settings
>>> settings.BASE_DIR
PS: If you named your template folder with another name, you would change it here too.
In django 3.1, go to setting of your project and import os
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Contrary to some answers posted in this thread, adding 'DIRS': ['templates'] has no effect - it's redundant - since templates is the default path where Django looks for templates.
If you are attempting to reference an app's template, ensure that your app is in the list of INSTALLED_APPS in the main project settings.py.
INSTALLED_APPS': [
# ...
'my_app',
]
Quoting Django's Templates documentation:
class DjangoTemplatesĀ¶
Set BACKEND to 'django.template.backends.django.DjangoTemplates' to configure a Django template engine.
When APP_DIRS is True, DjangoTemplates engines look for templates
in the templates subdirectory of installed applications. This generic name was kept for backwards-compatibility.
When you create an application for your project, there's no templates directory inside the application directory. Django admin doesn't create the directory for you by default.
Below's another paragraph from Django Tutorial documentation, which is even clearer:
Your projectā€™s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a ā€œtemplatesā€ subdirectory in each of the INSTALLED_APPS.
In django 2.2 this is explained here
https://docs.djangoproject.com/en/2.2/howto/overriding-templates/
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
...,
'blog',
...,
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
...
},
]
basically BASE_DIR is your django project directory, same dir where manage.py is.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
By default django looks for the template folder in apps. But if you want to use template folder from root of project, please create a template folder on root of project and do the followings in settings.py:
import os
TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
You can easily add template folder in settings.py folder, os.path is deprecated in django 3.1, so you can use path instead of os.path. You just have to import path in settings.py, you have to specify the base directory, then you have to specify template path, and last but not the least, you have to add template folder path in TEMPLATES = [{}], for example:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = Path(BASE_DIR, 'templates') (you can name TEMPLATE_DIR to any name)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
One interesting thing I noted for templates searching
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
#'DIRS': [os.path.join(BASE_DIR,"templates")],
'DIRS': [],
'APP_DIRS': True,
if the app folder have templates sub-folder then only it is searched and listed under Template-loader postmortem
If app/templates do not exist, it is not listed in error messages. Understanding this will prevent newbee to add template folders via DIRS directive
This is for DJANGO version 4.x.x
To add templates folder open file settings.py and modify
'DIRS': [BASE_DIR / 'templates'],
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

Categories

Resources