Serve django static files for production service and solve missing admin page css problem.

It works perfectly on dev version of my django site. But when I deploy it to production (served by apache), I realized that css is missing for admin pages. Then I digged a little deeper to see what I could do to solve this issue. It actually quite simple. There are two files you need to modify.

  1. Modify settings.py.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    ...
    ...
    # create 'static' folder in your app if you haven't done so,
    # which will be in the same level of your settings.py file.
    STATIC_ROOT = os.path.join(os.path.dirname(__file__), 'static/')
    ...
    STATIC_URL = '/static/'
    ...
    INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    )

here STATIC_ROOT will be the folder where django will copy all admin static files. STATIC_URL will corresponding to the alias name in your apache config file. Don’t worry, keep reading and it will be clear to you.

  1. Go to your django site directory and run
    1
    $ python manage.py collectstatic

This will copy all static files including admin css, image, js files into your STATIC_ROOT. Now check your “static” folder, you should see “admin” folder which has “css”, “img” and “js” sub-folders.

  1. Modify corresponding apache config files under /etc/apache2/sites-available/ folder.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    <VirtualHost *:80>
    ...
    ...
    ServerAdmin xxx
    ServerName xxx
    ServerAlias xxx
    Alias /static/ /dir/to/your/static/
    ...
    </VirtualHost>

where “/static/“ is your STATIC_URL and “/dir/to/your/static/“ will be the location of your “static” folder which is your STATIC_ROOT.

  1. You are all set! Restart your apache and checkout your admin page.

References: