Django: Can't render STATIC_URL from settings in template

12,427

Solution 1

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.

Solution 2

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' %}
Share:
12,427

Related videos on Youtube

user544871
Author by

user544871

Updated on January 09, 2021

Comments

  • user544871
    user544871 over 3 years

    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?

  • Dave
    Dave about 13 years
    you may also need to add the static context processor
  • Pierre-Adrien
    Pierre-Adrien over 12 years
    Thanks for the render shortcut tip :)
  • rburhum
    rburhum over 12 years
    After punishing myself for some time I found your little comment "django.core.context_processors.static" to be the most useful thing I have heard in the past 24 hours. THANK YOU
  • Fábio Diniz
    Fábio Diniz over 12 years
    @rburhum. Haha, great! I'm glad to help!
  • eLRuLL
    eLRuLL about 11 years
    I don't have the TEMPLATE_CONTEXT_PROCESSORS variable in my settings.py file, what is happening? or what should i do?
  • Fábio Diniz
    Fábio Diniz about 11 years
    @eLRuLL Well maybe it was deleted, check the docs and create it again