I have a html file called base.html inside a folder called html. There are two directories at the same level as html - js and css which contain static resources. The base.html refers those static resources through relative paths, like
<script type="text/javascript" src="../js/debounce.js"></script>
<link rel="stylesheet" href="../css/base.css">
It works as expected. Now I copied the entire directory structure to my django project. This is how the root folder ecom looks like:
The customviews directory contains the html, js and css directories, as well as a myview.py file, which is refered to in the urls.py file within the ecom subdirectory as:
from customviews.myview import *
urlpatterns = [url(r'^admin/', admin.site.urls),
url(r'^time/$', current_datetime),
url(r'^base/', base)]
The base method in myviews.py simply runs as follows:
def base(request):
return render_to_response("base.html")
And the relevant part of settings.py looks like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'DIRS': [os.path.join(dirfunc(dirfunc(__file__)), 'templates').replace('\\', '/'),
os.path.join(dirfunc(dirfunc(__file__)), 'customviews/html').replace('\\', '/'),
os.path.join(dirfunc(dirfunc(__file__)), 'customviews/js').replace('\\', '/'),
os.path.join(dirfunc(dirfunc(__file__)), 'customviews/css').replace('\\', '/')],
'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',
],
},
},
]
When I fire up the server and load base, only the basic html is rendered, the css and js are missing. How do I load both?
You don't need to be including the static resource folders in your template dirs. What you do need to do is set your STATICFILES_DIRS under settings and include a static tag in your templates are calling those resources.
Related
I'm learning Django from 'Mastering Django: Core' book and now I'm
stucked in this third chapter of the book which describes about the Django template.
The problem I'm facing is I can't load a template from a specific directory because it gives me this "TemplateDoesNotExist at /home/" error.
Here is my project directory :
mywebsite/
mywebapp/
...
...
views.py
...
temp/
template.html
Here is TEMPLATES list from settings.py :
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/home/temp'],
'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',
],
},
},
]
And finally here's my view :
from django.template.loader import get_template
def home(request):
t = get_template("template.html")
c = Context({'heading':'Welcome to MyWebsite.',
'name':'Arya Stark','age':19})
return HttpResponse(t.render(c))
Note: The template I'm using in this view is in the temp directory.
So, can you please explain me why would that error happen?
You've set DIRS to "/home/temp", but as you've clearly shown in your directory structure, your templates are in "mywebsite/temp". You'll probably need to use the full path there, or at least os.path.join(BASE_DIR, 'temp').
First of all, check if in your settings.py BASE_DIR is declared, if it is,
then check,
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Also, in your DIRS in TEMPLATES,
'DIRS' : [BASE_DIR + '/temp/',]
This should do the trick,
Also, django as default checks for the sub-directory templates in your app-directory and project-directory as well, when you APP_DIRS = True.
I'm working on an Open Source Django app and created some design for it. Now a customer wants to use it's own, copyrighted, design. After reading the Django docs I created a separate, private, GIT repository that I want to use for the new design. I got it almost working by adding 2 items to the settings; an extra entry to look for templates in a folder "funder_custom_templates" and an extra entry to look for static files in the same location. This is how I configured TEMPLATES and STATICFILES_DIR:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(PROJECT_DIR, '..', '..', 'funder_custom_templates'),
os.path.join(PROJECT_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',
'fundraiser.context_processors.cart',
],
},
},
]
STATICFILES_DIRS = [
os.path.join(PROJECT_DIR, '..', '..', 'funder_custom_templates','static'),
os.path.join(PROJECT_DIR, 'static'),
]
This works for overriding the base design located in the PROJECT_DIR/templates/base.html, when I create funder_customer_templates/base.html and for all the static files as expected. But I also want to override app specific template files like blog/templates/blog/blog_index_page.html
I tried to put these files in the root of funder_custom_templates and I tried to mimic the app folders structure in funder_custom_templates but that doesn't load the app specific templates. Is there a way to solve this?
Example project files, with the folder structure, located at: https://github.com/acidjunk/funder/tree/develop/
Since you are using the app_directories.Loader class to load templates (specified by setting 'APP_DIRS': True,), then for app specfic templates Django will iterate over your INSTALLED_APPS setting looking for a specific template file. The important thing here is that it does so in order.
So if you want to override blog/templates/blog/blog_index_page.html then you will need to have a custom_blog/templates/blog/blog_index_page.html inside an application that comes before blog.
I recommend wrapping up all custom static resources in their own django application and python package. This way you can simply install the package from its private repo and add it to the list of installed apps to override any static content and templates.
See Django's docs for more details on template loading: https://docs.djangoproject.com/en/1.9/ref/templates/api/#django.template.loaders.app_directories.Loader
I have the following directory structure in my django 10 project:
/my-project/ # project dir
+app1
+templates
+admin
base.html
404.html
500.html
My templates attribute looks like this in settings:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'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',
'common.context_processors.site_info',
],
},
},
]
My custom base.html displays on my local machine. When I upload this to my production server it no longer overrides and uses the base.html file in project folder.
I have changed around the order of apps suggested here and tried printing the dirs element of the templates attribute which prints "templates/" like here.
Does anyone know how I can get this to work on my production environment?
You must use absolute path in your settings to avoid issues. For example:
import os
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..', '..')
# depending where your settings.py live
...
'DIRS': [
os.path.join(PROJECT_ROOT, 'templates'),
],
I am using windows, new to Django, trying to learn it.
Right now I am just trying to set up a template, views, url - and load the template in my browser. Should be simple.
I have a project folder. An app folder. A templates folder. My templates folder contains page.html which is an html file that just says "hi".
my urls is properly configured to point to my views
I have 2 views.
def frontpage(request):
fp = open('C:/EclipseWorkspace64/Project/templates/page.html')
page = Template(fp.read())
return HttpResponse(page)
def otherpage(request):
page = get_template('page.html')
return HttpResponse(page)
The first view loads my template fine when I go to the URL.
The second view does not. It gives me: [Errno 22] Invalid argument: 'C:\EclipseWorkspace64\Project\:\page.html'
This is templates in my settings:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': 'C:/EclipseWorkspace64/Project/templates/',
'APP_DIRS': False,
'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',
],
},
},
]
I don't understand why I get this error. What am I doing wrong? Why does the first view load but the second one doesn't? I have followed instructions in the django book on how to set up my settings file to a tee.
I have CSS file at /ecomstore/static/css.css
I have already linked the css to the base.html within head tags by
<link rel="Stylesheet" type="text/css" href="/static/css.css" />
My urls.py file:
from django.conf.urls import include, url
from django.contrib import admin
from ecomstore import settings
from django.contrib.staticfiles import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^catalog/','preview.views.home'),
# url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
# { 'document_root' : '/home/yogesh/ecomstore/static' })
]
urlpatterns = [
# other commented code here
url(r'^catalog/?','preview.views.home'),
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',{ 'document_root' : '/home/yogesh/ecomstore/static/' }),
]
Settings.py file
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [os.path.join(CURRENT_PATH, 'templates')],
'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',
],
},
},
]
Static settings:
STATIC_URL = '/static/'
STATIC_ROOT = "/home/yogesh/ecomstore/static/"
Despite all this stuff i dont know why my css template is not loading. Also in the terminal i am getting the following indicating some sort of error.
[24/Nov/2015 11:11:36] "GET /static/css.css HTTP/1.1" 404 1735
Use {% static %} template tag:
{% load staticfiles %}
Configure static files dir in your settings and do not hardcode the path in your urlconf:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
'/var/www/static/',
)
Make sure you're serving static files during development:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Check that static file dir /home/yogesh/ecomstore/static/ is readable by your django process.
Static files
Store your files in /ecomstore/static/ecomstore/css.css instead of /ecomstore/static/css.css because Django look by default in all folders <app_name/static/<app_name>, then you don't have to had these folder in STATICFILES_DIRS variable.
Django documentation :
Store your static files in a folder called static in your app. For
example my_app/static/my_app/myimage.jpg.
Read this for more
information and configure your project : Managing static files
Templates
You did also a mistake in the configuration of your template. When you use os.path.json function, you don't have to have a / at the last folder. Just use os.path.join(BASE_DIR, 'templates')
Serving static file during development
Concerning serving static files, if you use the django built-in server, you don't have to configure anything, Django serve them by default. However, if you use gunicorn or uWSGI, yes you have to configure your project to serve static files.
You have to add this in your main <project_name>/<project_name>/urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Now, your server will server static file based on STATIC_URL that you configured in your <project_name>/<project_name>/settings.py file.
Read this for more information : Serving static files during development