Search code examples
htmlcssdjangorenderingstylesheet

Render CSS in Django


I am trying to get the CSS sheet to load on my development computer. It is in the media directory as media/base.css. In my base/base.html template, I have:

<link href="media/base.css" rel="stylesheet" type="text/css" />

I found this page, but that didn't fix it. Any ideas?


Solution

  • if media/ is your project media directory, then in the template use

    <link href="{{ MEDIA_URL }}base.css" rel="stylesheet" type="text/css" />
    

    this is considering you have passed RequestContext to your template, ex:

    def some_view(request):
        # ...
        return render_to_response('my_template.html',
                                  my_data_dictionary,
                                  context_instance=RequestContext(request))
    

    You will also need to have static urls served when running on the localdev server. Include this in your urls.py:

    from django.conf import settings
    if settings.DEBUG:
        urlpatterns += patterns('',
                                url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL[1:],
                                    'django.views.static.serve',
                                    {'document_root': settings.MEDIA_ROOT, 'show_indexes': True})
                                )