How do I make Django "see" CSS?

Asked

Viewed 7,033 times

6

I am writing a Django and Python application, and I have a problem in the part of templates, running locally Django found the template and I was able to visualize her through the localhost:8080/home, happens that the stylesheet (CSS) is not being downloaded (located) by Django, it is displaying the HTML template 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>
      <script src="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 browser developer mode that the 3 CSS files are not being found, this returning 404 not found.

My python is Python27 Django is 1.6.2

  • "I visualized by browser developer mode that the 3 CSS files are not being found, this returning 404 not found." Can you see the CSS path there? If so, check if it is in the right place.

  • The CSS path is correct!

2 answers

6

Since your project is structured like this:

inserir a descrição da imagem aqui

In short, how it should be configured to load your CSS:

py Settings.

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

STATIC_URL = '/static/'

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

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">

6


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

1) Set the path to static resources

There is a variable that you add to settings.py, calling for STATICFILES_DIRS, where you can add the paths to your static resources (css files, js, images, etc). 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 the python manage.py collecstatic to copy the files to the right folder.

2) Set static resource URL

In the archive urls.py, it is necessary to make a modification so that the Urls are recognized. Thus:

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 template

Also missing prefix for static files in CSS URL.

You can solve it like this:

Before:

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

Afterward:

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

Or use the oldest method:

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

On this Django documentation page (in English), are more details regarding the configuration of static files.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.