How do I make Django "see" CSS?

5

I'm writing a Django and Python application, and I'm having a problem     in the templates part, running locally Django found the template and     I was able to visualize it through localhost:8080/home , it happens that the     style sheet (CSS) is not being downloaded (localized) by Django,     it is displaying the template in HTML only.

The project tree is as follows:

Library
  |_ __init__.py
  |_ admin.py
  |_ models.py
  |_ tests.py
  |_ views.py
  |_ urls.py
  |_ templates
      |_ templates
          |_ index.html
          |_ base.html
          |_ css
          |_ js
          |_ fonts

My settings.py:

# -*- coding: utf-8 -*-

"""
Django settings for Chameleon project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

#PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gb)bi45$q*#()1gbf_1td3x7+7#%3zk4%&)$^f6@8bpndb$a12'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = DEBUG

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin', #Sistema de administracao Backend
    'django.contrib.auth', #Sistema de autenticao
    'django.contrib.contenttypes', #Tipos de conteudo 
    'django.contrib.sessions', #Trata as sessoes
    'django.contrib.messages', #Gerencia mensagens de erro sucesso etc
    'django.contrib.staticfiles', #Gerencia arquivos estaticos (html, CSS, JavaScript)
    'Library', #Adicionando nome do projeto para criação das tabelas no DB
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'Chameleon.urls'

WSGI_APPLICATION = 'Chameleon.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'USER': '', 
        'PASSWORD':'',
        'HOST': '',
        'PORT': '',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'pt-BR'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'


MEDIA_ROOT = os.path.join

My views.py:

# -*- coding: utf-8 -*-    
#from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response

# Create your views here.   
def home(request):
    return render_to_response('templates/index.html')

My HTML index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Bootstrap Icone da pagina -->
    <link rel="shortcut icon" href="">

    <title>Chameleon</title>

    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap-responsive.css" rel="stylesheet" >
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="css/signin.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy this line! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script><scriptsrc="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>

  <body>

    <div class="container">

      <form class="form-signin" role="form">
        <h2 class="form-signin-heading">Please sign in</h2>
        <input type="email" class="form-control" placeholder="Email" required autofocus>
        <input type="password" class="form-control" placeholder="Senha" required>
        <label class="checkbox">
          <input type="checkbox" value="remember-me"> Lembre-me
        </label>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
      </form>

    </div> <!-- /container -->


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
  </body>
</html>

I visualized by the browser's developer mode that the 3 CSS files     not found, is returning 404 not found.

My python is Python27 Django is 1.6.2

    
asked by anonymous 07.05.2014 / 18:07

2 answers

5

I understand that three things are missing to solve your problem:

1) Define the path to static resources

There is a variable that you add in settings.py , called STATICFILES_DIRS , where you can add paths to your static resources (css, js, images, etc files). For example:

# Additional locations of static files
STATICFILES_DIRS = (
   '/caminho/para/recursos/estaticos/aqui',
)

On the test server this is enough, but in production it is also necessary to run python manage.py collecstatic to copy the files to the right folder.

2) Define the URL of static resources

In the urls.py file, you need to make a modification so that the URLs are recognized. So:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... seus URLs aqui
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

3) Add prefix to static files in the template

The prefix for static files in the CSS URL is also missing.

You can solve it like this:

Before:

<link href="css/bootstrap-responsive.css" rel="stylesheet">

Then:

{% load staticfiles %}
<link href="{% static "css/bootstrap-responsive.css" %}" rel="stylesheet">

Or use the older method:

<link href="{{STATIC_URL}}css/bootstrap-responsive.css" rel="stylesheet">

On this page of the Django documentation , further details are configuration of static files.

    
07.05.2014 / 19:25
4

Since your project is structured like this:

Insummary,howshoulditbeconfiguredtoloadyourCSS:

settings.py

importosBASE_DIR=os.path.dirname(os.path.dirname(__file__))STATIC_URL='/static/'STATICFILES_DIRS=(os.path.join(BASE_DIR,"projeto/static"),
    # '/var/www/static/',
)

urls.py

from django.conf.urls.static import static
from django.conf import settings

urlpatterns = patterns('',
    #suas urls
)    
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Template

Always add at the beginning of your HTML {% load staticfiles %}

{% load staticfiles %}
<link href="{% static "css/bootstrap-responsive.css" %}" rel="stylesheet">
<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet">
    
07.05.2014 / 20:25