Escribiendo su primera aplicación en Django, parte 6¶
This tutorial begins where Tutorial 5 left off. We’ve built a tested web-poll application, and we’ll now add a stylesheet and an image.
Aparte del HTML generado por el servidor, las aplicaciones Web por lo general tienen que servir archivos adicionales tales como imágenes, JavaScript o CSS necesarios para renderizar la página web completa. En Django, nos referimos a estos archivos como «archivos estáticos».
For small projects, this isn’t a big deal, because you can keep the static files somewhere your web server can find it. However, in bigger projects – especially those comprised of multiple apps – dealing with the multiple sets of static files provided by each application starts to get tricky.
Eso es para lo que django.contrib.staticfiles
es: recolecta los archivos estáticos de cada una de sus aplicaciones (y de cualquier otro lugar que usted especifique) en un solo lugar que se puede servir fácilmente en la producción.
Dónde obtener ayuda:
If you’re having trouble going through this tutorial, please head over to the Getting Help section of the FAQ.
Personalice la apariencia de su aplicación¶
En primer lugar, cree un directorio llamado static
en su directorio polls
. Django buscará archivos estáticos allí, del mismo modo cómo Django encuentra las plantillas dentro de polls/templates/
.
La opción STATICFILES_FINDERS
de Django contiene una lista de buscadores que saben cómo hallar archivos estáticos de diversas fuentes. Uno de los predeterminados es AppDirectoriesFinder
que busca un subdirectorio «static» en cada una de las INSTALLED_APPS
, como el que está en polls
que acabamos de crear. El sitio administrativo utiliza la misma estructura de directorios para sus archivos estáticos.
Within the static
directory you have just created, create another directory
called polls
and within that create a file called style.css
. In other
words, your stylesheet should be at polls/static/polls/style.css
. Because
of how the AppDirectoriesFinder
staticfile finder works, you can refer to
this static file in Django as polls/style.css
, similar to how you reference
the path for templates.
Espacio de nombres de archivo estático
Just like templates, we might be able to get away with putting our static
files directly in polls/static
(rather than creating another polls
subdirectory), but it would actually be a bad idea. Django will choose the
first static file it finds whose name matches, and if you had a static file
with the same name in a different application, Django would be unable to
distinguish between them. We need to be able to point Django at the right
one, and the best way to ensure this is by namespacing them. That is, by
putting those static files inside another directory named for the
application itself.
Introduzca el siguiente código en esa hoja de estilo (polls/static/polls/style.css
):
li a {
color: green;
}
A continuación, agregue lo siguiente en la parte superior de polls/templates/polls/index.html
:
{% load static %}
<link rel="stylesheet" href="{% static 'polls/style.css' %}">
La etiqueta de plantilla {% static %}
genera la URL absoluta de los archivos estáticos.
That’s all you need to do for development.
Start the server (or restart it if it’s already running):
$ python manage.py runserver
...\> py manage.py runserver
Reload http://localhost:8000/polls/
and you should see that the question
links are green (Django style!) which means that your stylesheet was properly
loaded.
Agregando una imagen de fondo¶
Next, we’ll create a subdirectory for images. Create an images
subdirectory
in the polls/static/polls/
directory. Inside this directory, add any image
file that you’d like to use as a background. For the purposes of this tutorial,
we’re using a file named background.png
, which will have the full path
polls/static/polls/images/background.png
.
Then, add a reference to your image in your stylesheet
(polls/static/polls/style.css
):
body {
background: white url("images/background.png") no-repeat;
}
Reload http://localhost:8000/polls/
and you should see the background
loaded in the top left of the screen.
Advertencia
The {% static %}
template tag is not available for use in static files
which aren’t generated by Django, like your stylesheet. You should always
use relative paths to link your static files between each other,
because then you can change STATIC_URL
(used by the
static
template tag to generate its URLs) without having to modify
a bunch of paths in your static files as well.
Estos son los fundamentos. Para más detalles sobre la configuración y otra información que se incluye con el framework consulte la guía paso-a-paso de los archivos estáticos y la referencia de los archivos estáticos. Implementación de archivos estáticos habla sobre cómo utilizar los archivos estáticos en un servidor real.
Cuando esté familiarizado con los archivos estáticos, lea la parte 7 de este tutorial para aprender a personalizar el sitio administrativo generado automáticamente de Django.