Glory to Russia
Glory to Russia

Reputation: 18712

How to use Twitter Bootstrap in a Django application

I want to use Twitter Bootstrap in my Django application and for this purpose modified the template in the following way:

<!DOCTYPE html>

<html>
<head>
    <title>{{ genplan.name }}</title>
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
    <h1>{{ genplan.name }}</h1>
    <ol>
        {% for cur_goal in goals %}
            <li>{{ cur_goal.description }}</li>
        {% endfor %}
    </ol>

    ...
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>
</html>

MEDIA_ROOT and MEDIA_URL are set correctly.

MEDIA_ROOT = 'D:/dev/ccp/ccp-gp/media'
MEDIA_URL = '/media/'

However, nothing has changed after I added the Bootstrap stylesheets (the look of that page didn't change) and I suppose that Django doesn't find the Bootstrap resources.

What may have caused this problem?

Update 1:

When I use this code in urls.py

urlpatterns = patterns('',
    (r'^$', 'ccp_gp.general_plans.views.home'),     (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT})     )

Python complains about undefined settings variable.

Upvotes: 5

Views: 9552

Answers (1)

bikeshedder
bikeshedder

Reputation: 7487

You need to use the MEDIA_URL when loading the css and js:

<link href="{{ MEDIA_URL }}css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="{{ MEDIA_URL }}js/bootstrap.min.js"></script>

Unless you have to use an old Django version which does not come with the static files app I would recommend to use STATIC_URL instead and put the files into the static directory of your app.

<link href="{{ STATIC_URL }}css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="{{ STATIC_URL }}js/bootstrap.min.js"></script>

As stated in the comments your {{ MEDIA_URL }} is empty. In order to fix that make sure that the TEMPLATE_CONTEXT_PROCESSORS settings contains the 'static' and 'media' context processor. Unless you have modified the TEMPLATE_CONTEXT_PROCESSORS settings this is already the case.

The template context processors are only used when rendering a template with the RequestContext. Starting with Django 1.3 the best way to do this is by using a TemplateResponse.

For example:

from django.template.response import TemplateResponse

def index(request):
    genplan = ...
    goals = ...
    return TemplateResponse(request, 'index.html', {
        'genplan': genplan,
        'goals': goals,
    })

For the files in the MEDIA_DIR to be delivered via the the development server (manage.py runserver) you can add the following code to your urls.py:

from django.conf import settings

if settings.DEBUG:
    urlpatterns += (
        url(r'^media/(.*)$', 'django.views.static.serve',
                    {'document_root': settings.MEDIA_ROOT}),
    )

Upvotes: 9

Related Questions