Django: Can't render STATIC_URL from settings in template

Question:

http://docs.djangoproject.com/en/dev/howto/static-files/

This suggests that I can use STATIC_URL in my template to get the value from settings.py.

Template looks like this:

<link href="{{STATIC_URL}}stylesheets/tabs.css" rel="stylesheet" type="text/css"  media="screen" />

Settings.py looks like this:

STATIC_ROOT = ''
STATIC_URL = '/static/'

When I go to the page I just get <link href="stylesheets/tabs.css" i.e. no STATIC_URL.

What am I missing?

Asked By: user544871

||

Answers:

You have to use context_instance=RequestContext(request) in your render_to_response, for example:

return render_to_response('my_template.html',
                          my_data_dictionary,
                          context_instance=RequestContext(request))

Or use the new shortcut render

As Dave pointed out, you should check if django.core.context_processors.static is in your TEMPLATE_CONTEXT_PROCESSORS variable in settings.py. As the docs said, it`s there by default.

Answered By: Fábio Diniz

It is not recommended to directly use the STATIC_URL variable. See the accepted answer in this question

Instead of

{{STATIC_URL}}stylesheets/tabs.css

use

{% load staticfiles %}
{% static 'stylesheets/tabs.css' %}
Answered By: aliteralmind

I have the same problem, solved like this:

in settings.py
add:

django.template.context_processors.static

here:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': TEMPLATE_DIRS,
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.template.context_processors.static',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},

]

Answered By: iqmaker
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.