Thursday, 23 March 2017

django templates and static files


django templates and static files settings
Django template configurations

Django templates:

Django templates are just HTML files. Django creates HttpResponse for a request by rendering the given template(HTML file) with given context data. 

Django supports different types of template engines like JINJA, GENSHI, MAKO etc., Django also have it's own template engines. Template engines are configured with  "TEMPLATES" setting. It contains a list of template engines. Each template engine settings are defined in dictionary like below.
TEMPLATES = [
  {
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': ["templates"],
    'APP_DIRS': True,
    'OPTIONS': {
        # ... some options here ...
     },
  },
]
We can observe in above configuration is that it contains a template engine(dictionary of settings) inside a list.
BACKEND:
It is a python path to a template engine class. It is used for rendering the templates.
Django has two built-in template engines.
  1. django.template.backends.django.DjangoTemplates 
  2. django.template.backends.jinja2.Jinja2
Both backends works fine, but they differ in template language syntax.
DIRS:
We provide "template path" to template engine. It will search for template with given path in directories (APP_DIRS, DIRS). It considers the apps from "INSTALLED_APPS" configuration.
APP_DIRS:
By default it is set to "True". This allow template engine to look for template in applications template directories.
OPTIONS: 
 It allows us to define options like template context processors, template loaders.

Django static files:

Static files, the term "static" itself tells that they do not change with time.
Usually static files includes javascript, css, images, etc.
Configuration for static files
  1. Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS
  2. Define STATIC_URL = '/static/' in settings.py file.
  3. By default django finds the static files in "static" directory under apps or in root directory. If you want to specify other directories as "static" you should add below configurations to settings.py file
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

Serving static files during development

Add the below code in root urls.py
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
]
urlpatterns += static(
    settings.MEDIA_URL,
    document_root=settings.MEDIA_ROOT
)

Serving files uploaded by a user during development

Add the below code in root urls.py
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
]

urlpatterns += static(
    settings.MEDIA_URL,
    document_root=settings.MEDIA_ROOT
)


EmoticonEmoticon