Skip to content

Instantly share code, notes, and snippets.

@jueti
Last active March 23, 2019 11:05
Show Gist options
  • Save jueti/0d8a022acd436de8396067140409c10f to your computer and use it in GitHub Desktop.
Save jueti/0d8a022acd436de8396067140409c10f to your computer and use it in GitHub Desktop.
Django config (last update 2018-5-21)

OpenStack

Serving static files

see: The staticfiles app | Django

  1. open settings.py and set
    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, "static")
    
  2. add your app in INSTALL_APP and store your static files in the application subdirectory named static
    project/app/static/example.jpg
    
  3. collect all static files
    django-admin collectstatic
    
  4. config web server to server static files
    1. default web server of Django (invalid whe DEBUG = False)
      1. add the url pattern of static files:
        from django.conf import settings
        from django.conf.urls.static import static
        urlpatterns = [
            # other URL conf
        ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
        
    2. IIS + wfastcgi
      1. make a virtual directory
      2. delete the mapping to static dir
  5. use the static tag in your templates
    {% load static %}
    <img src="{% static "my_app/example.jpg" %}" alt="My image"/>
    

Last edit: 2018-05-21 19:37:04

Customizing error views

see: Customizing error views | Django

  1. open settings.py and set:
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                # other options
            },
        }
    ]
    

    note APP_DIRS: True would enable the engine to look for templates inside installed applications in order. it is conventional that templates stored in application subdirectory named templates

  2. add your app in INSTALL_APP and store your template files in the application subdirectory named templates
    project/app/templates/example.html
    
  3. use template in views
    from django.shortcuts import render
    
    
    def my_view(request):
        # other code
        return render(request, 'example.html', {'foo': 'bar', }, content_type='application/xhtml+xml')
    

    the example equal to

    from django.http import HttpResponse
    from django.template import loader
    
    def my_view(request):
        # other code
        t = loader.get_template('app/example.html')
        c = {'foo': 'bar'}
        return HttpResponse(t.render(c, request), content_type='application/xhtml+xml')
    

    note that specify app/example.html when multiple files are available.

  4. django automatically load 404.html as the 404 error page when DEBUG = False so that you can move your custom 404 page to app/templates/404.html. alternative solution is custom error views.

    i. specify the handler as seen below in your URL conf (setting have no effect anywhere else)

    handler404 = 'app.views.custom_page_note_found_view'
    

    Source code for django.views.defaults.page_not_found | Django

Last edit: 2018-05-21 22:49:23

Question & Answer

Can't serving static files?

  1. can't load CSS, JS, img, cause Django can't find your static files. You can execute the following command to display the search path when Django load static files.
    python manage.py findstatic --verbosity 2 css/styles.css
    
  2. once static files outside the search locations, you can increase the searching locations, and also move file to exists locations. there are two method to increase locations:
    1. add app name to the setting list named INSTALLED_APP in settings.py. and the new location is project/app_name/static/
      INSTALLED_APP = [
          # others app,
          'app_name',
      ]
      
    2. add new location to STATICFILES_DIRS in settings.py. this setting in invalid when DEBUG = False, and conflict to another setting named STATIC_ROOT when the same location existed.
      STATICFILES_DIRS = (
          os.path.join(BASE_DIR, 'staticfiles'),
      )
      

last edit: 2018-05-21 19:37:10

from django.urls import path
from django.views.generic import RedirectView
urlpatterns = [
path('favicon.ico', RedirectView.as_view(url='{}'.format(settings.STATIC_URL + 'favicon.ico'), permanent=True)),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment