So ive been trying to setup a django settings module that will check the environment variable and load settings.
Heres what my settings module looks like
/templates
home.html
/settings
base.py
prod.py
dev.py
test.py
base.py
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = [
os.path.join(PROJECT_ROOT, "templates"),
]
urls.py
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
url(r"^$", direct_to_template, {'template' : 'home.html' }, name="home"),
)
When I had all of my settings in one file, this worked just fine, but since I split the files up I get the error:
TemplateDoesNotExist at /
home.html
Template-loader postmortem
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
/Users/Tulsa/Apps/tulsa-applications-co/tulsa/tulsa/settings/templates/home.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/django/contrib/auth/templates/home.html (File does not exist)
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/django/contrib/admindocs/templates/home.html (File does not exist)
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/grappelli/templates/home.html (File does not exist)
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/django/contrib/admin/templates/home.html (File does not exist)
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/pagination/templates/home.html (File does not exist)
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/djangosaml2/templates/home.html (File does not exist)
/Users/Tulsa/Apps/tulsa-applications-co/tulsa/tulsa/apps/profiles/templates/home.html (File does not exist)
/Users/Tulsa/.Apps/tulsa_io/lib/python2.7/site-packages/debug_toolbar/templates/home.html (File does not exist)
Using loader django.template.loaders.eggs.Loader:
what am i missing here?
All answers above require of configuring TEMPLATE_DIRS or TEMPLATE_LOADERS, which is not necessary and correct. You just have to put YOUR application to the INSTALLED_APPS.
For example, if your application is in the MyMegaApp (where settigs.py resides), in other words you have a project structure like below
MyMegaApp
MyMegaApp
templates
index.html
settings.py
manage.py
Then you have to add your app like this
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'MyMegaApp'
)
After that your index.html template will be found in MyMegaApp/templates folder
The problem here is, in your settings, your PROJECT_ROOT evaluates to the directory which runs manage.py.
You may do this for TEMPLATE_DIRS settings
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
print PROJECT_ROOT
Now, append ../../ relative to the PROJECT_ROOT. Something like this:
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../'))
TEMPLATE_DIRS = [
os.path.join(PROJECT_ROOT, "templates"),
]
Change your PROJECT_ROOT to:
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
And make sure your TEMPLATE_LOADERS variable is set properly.
Explanation:
abspath gives you the full path of the base.py, i.e., /home/some-path/project-folder/settings/base.py
Therefore, first dirname gives you the dir path name of the given path (obtained above), i.e., /home/some-path/project-folder/settings/
And then, the second dirname gives you the dir path name of the given path (obtained above), i.e., /home/some-path/project-folder/
So, now when you join this path to templates, everything starts working fine.
For more refer python docs.
can you test as below?
i think your code would set PROJECT_ROOT as '/some/path/to/settings'
from os.path import dirname, abspath, normpath, join
PROJECT_ROOT = dirname(dirname(abspath(__file__)))
TEMPLATE_DIRS = (
normpath(join(PROJECT_ROOT, 'templates')),
)
Include this in settings
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(SITE_ROOT, 'appname/templates'),
)
Add this to urls.py
from django.conf.urls.defaults import *
from django.views.generic.simple.direct_to_template import direct_to_template
from appname.views import *
call url by
urlpatterns = patterns('django.views.generic.simple',
(r'^foo/$', 'direct_to_template', {'template': 'foo_index.html'}),
(r'^foo/(?P<id>\d+)/$', 'direct_to_template', {'template': 'foo_detail.html'}),
)
Related
I would like to use django staticfiles, but unfortunately I can't get it to serve to images locally.
This is what I have done so far:
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'content.apps.ContentConfig',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
When I do a print(os.path.join(BASE_DIR, 'staticfiles')) I see the correct local path.
urls.py:
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
import content.views
urlpatterns = [
path('admin/', admin.site.urls),
path('', content.views.index, name='index'),
path('/about', content.views.about, name='about'),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
templates:
{% load static %}
...
{% static "css/master.css" %}
resolves to
/static/css/master.css
[EDIT]
URL PATTERN looks like this
Using the URLconf defined in website.urls, Django tried these URL
patterns, in this order:
admin/
[name='index']
/about [name='about']
^static/(?P<path>.*)$
Opening a file directly ends up to a 404-django-page.
After that, I ran ./manage.py collectstatic successfully.
I am using the Django Dev server e.g. ./manage.py runserver...
I am maybe missing something, just need an additional pair of eyes. Thanks.
Solved it by removing
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
and replacing it with
STATICFILES_DIRS = (os.path.join(BASE_DIR, "staticfiles"),)
I cant figure out how to make Azure App Service use css for admin panel.
In settings.py I included these:
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
But somehow css is still not working for the admin panel.
How can I fix this? As far as I know Oryx which works under Azure App Service should automatically run
python manage.py collectstatic
Any ideas?
EDIT:
Installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'licenses_api',
]
There are something to check might help:
Click F12 on your Admin page to check if it is the 404 Not Found error.
Check the static files exist in your azure web app or not. You could see it in https://{your-web-app}.scm.azurewebsites.net/wwwroot/ site.
Check if your file structure match with the settings.py. Any spell error would make the static file not found.
If your file exists well, you should check if you use them correctly in your code like this answer. Here is how he use:
from django.conf.urls.static import static
urlpatterns = [
path('myapp/', include('myapp.urls')),
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Firstly try to add these code lines to
settings.py
STATIC_URL = '/static/'
if DEBUG:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Then import these lines to the
urls.py
from django.conf.urls.static import static
from django.conf import settings
from django.conf.urls import url
from django.views.static import serve
Finaly you have to add these lines to urlpatterns in
urls.py
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
(If you have not already created a static file please make sure to create one before you try this)
It's worked severl times for me and hope this will work for you too 😊
well I'm working on a new Django project and am having a real hard time getting the index.html page to display correctly. Any advice on what to change to get it to display correctly?
I'm getting the error
TemplateDoesNotExist at /
index.html
my settings for each file are below.
myprojectname/myprojectname/settings.py
import os
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'templates/static')
TEMPLATE_DIRS = (
PROJECT_ROOT + '../templates'
)
myprojectname/myprojectname/urls.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', 'apps.views.index'),
url(r'^admin/', include(admin.site.urls)),
)
myprojectname/apps/views.py
from django.shortcuts import render_to_response
def index(request):
return render_to_response('index.html', locals())
I'm new to Django too so don't hate! :) I'll gladly admit I'm a noob...
Set up your template directories:
PROJECT_DIR = os.path.dirname(__file__)
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
Your folder structure should be similar to:
project_name/
project_name/
settings.py
templates/
index.html
The folder structure is especially important!
And define your template loaders if you haven't already:
TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)),
)
I've wrapped the standard loaders with cached.Loader, which funnily enough just caches pre-compiled templates.
Also, while I'm here, fix your root URL:
urlpatterns = patterns('',
url(r'^$', 'apps.views.index'),
Note the extra $ terminating the end of the regex, otherwise this first URL will match every single URL, and none of the others will get a chance to match.
Try this..
TEMPLATE_DIRS = (
PROJECT_ROOT + '../templates/'/
)
I am unable to use CSS and JS files in my django project.
Folder structure:
mysite/
mysite/mysite/settings.py
mysite/mysite/templates/base.html
mysite/mysite/assets/css/...
settings.py
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = 'static'
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',...)
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
base.html
running python manage.py collectstatic returns:
"Your STATICFILES_DIRS setting is not a tuple or list; "
django.core.exceptions.ImproperlyConfigured: Your STATICFILES_DIRS setting is not a tuple or list; perhaps you forgot a trailing comma?
You never manually put anything STATIC_ROOT. It is only a dumping ground for collectstatic in production; it shouldn't even exist in development.
All of your static resources need to go in one of your apps' static directories, or if you need project-wide resources, you must create an entirely different directory for that is not the same as either MEDIA_ROOT or STATIC_ROOT and add it to STATICFILES_DIRS:
STATICFILES_DIRS = (
os.path.join(PROJECT_PATH, 'assets'),
)
You can call it whatever you want; I typically use "assets". Just don't name it "static", "media", "site_media", etc., just to avoid confusion.
I want to use static files to load my css with runserver command. The problem is that i tried all the solution i found here on stackoverflow and also in django docs, but it doesnt works at all... I dont know what can i do...
If i set
STATIC_URL = '/static/'
STATIC_ROOT = 'C:\Users\Max\Works\www\mysite\mysite\static'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
)
I thought it was enough... Am i missing something?
Can you tell me what is the best setting for have static files in develompent envirnoment?
Thanks in advice...
EDIT(1)
I already putted in my template {{ STATIC_URL }}css/dark-grey.css" and ofc the css is in C:\Users\Max\Works\www\mysite\mysite\static\css\dark-grey.css, i really can't get what is wrong...
Use / slashes and NOT \ slashes in the path, even for windows paths.
In your settings.py
DEBUG=True
As per the docs:
This view is automatically enabled by runserver (with a DEBUG setting
set to True).
Using the URL pattern is a way to force it, which I personally don't even have to do in my project as long as DEBUG=True. You would always have DEBUG on when you are developing, and when you switch to production you aren't even using the development server anyways, so you would be pointing your production server to the static location.
This is a snippet of my static settings from my settings.py. I do not manually have to add that static view URL
import os
DEBUG = True
PROJECT_ROOT = os.path.dirname( __file__ )
PROJECT_NAME = os.path.basename(PROJECT_ROOT)
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/')
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_ROOT, 'web/'),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django.core.context_processors.static',
...
...
)
You need to add url patterns:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# ... the rest of your URLconf here ...
urlpatterns += staticfiles_urlpatterns()
See the documentation here
You also need to run the following command to get the static files moved into the right place (and for Django to know they're there):
python manage.py collectstatic
Full documentation on static files in Django 1.3 is here:
https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/