This advanced tutorial begins where Tutorial 8 left off. We’ll be turning our web-poll into a standalone Python package you can reuse in new projects and share with other people.
If you haven’t recently completed Tutorials 1–8, we encourage you to review these so that your example project matches the one described below.
Requiere mucho trabajo diseñar, crear, probar y mantener una aplicación web. Muchos proyectos de Python y Django comparten problemas comunes. ¿No sería genial si pudiéramos ahorrarnos algo de este trabajo repetido?
Reusability is the way of life in Python. The Python Package Index (PyPI) has a vast range of packages you can use in your own Python programs. Check out Django Packages for existing reusable apps you could incorporate in your project. Django itself is also a normal Python package. This means that you can take existing Python packages or Django apps and compose them into your own web project. You only need to write the parts that make your project unique.
Digamos que ha empezado un nuevo proyecto que necesitaba una aplicación de encuestas como la que hemos estado trabajando. ¿Cómo hace que esta aplicación sea reutilizable? Por suerte va bien encaminado. En el Tutorial 1, vimos como podíamos separar las encuestas de la URLconf a nivel de proyecto utilizando un include
. En este tutorial, adoptaremos las medidas para hacer que la aplicación sea fácil de utilizar en nuevos proyectos y quede lista para su publicación de manera que otros la instalen y usen.
¿Paquete? ¿Aplicación?
Un paquete de Python proporciona una forma de agrupar código Python relacionado para reutilizarlo de forma fácil. Un paquete contiene uno o más archivos de código Python (también conocidos como «módulos»).
Un paquete puede ser importado con import foo.bar
o from foo import bar
. Para que un directorio (como polls
) cree un paquete, debe contener un archivo especial __init__.py
, incluso si este archivo está vacío.
A Django application is a Python package that is specifically intended
for use in a Django project. An application may use common Django
conventions, such as having models
, tests
, urls
, and views
submodules.
Posteriormente, usamos el término empaquetamiento para describir el proceso de hacer que un paquete Python sea fácil de instalar para los demás. Sabemos que puede ser un poco confuso.
After the previous tutorials, our project should look like this:
djangotutorial/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
0001_initial.py
models.py
static/
polls/
images/
background.png
style.css
templates/
polls/
detail.html
index.html
results.html
tests.py
urls.py
views.py
templates/
admin/
base_site.html
You created djangotutorial/templates
in Tutorial 7, and polls/templates
in
Tutorial 3. Now perhaps it is clearer why we chose
to have separate template directories for the project and application:
everything that is part of the polls application is in polls
. It makes the
application self-contained and easier to drop into a new project.
El directorio polls
ahora se podría copiar en un nuevo proyecto de Django e inmediatamente ser reutilizado. Sin embargo, no está listo para ser publicado. Para ello, necesitamos empaquetar la aplicación para hacer más fácil que otros la instalen.
The current state of Python packaging is a bit muddled with various tools. For
this tutorial, we’re going to use setuptools to build our package. It’s
the recommended packaging tool (merged with the distribute
fork). We’ll
also be using pip to install and uninstall it. You should install these
two packages now. If you need help, you can refer to how to install
Django with pip. You can install setuptools
the same way.
El empaquetamiento en Python se refiere a la preparación de su aplicación en un formato específico que pueda ser fácilmente instalado y utilizado. Django mismo está empaquetado de forma muy similar a esta. Para una aplicación pequeña como polls este proceso no es muy complejo.
First, create a parent directory for the package, outside of your Django
project. Call this directory django-polls
.
Eligir un nombre para su aplicación
When choosing a name for your package, check PyPI to avoid naming
conflicts with existing packages. We recommend using a django-
prefix for package names, to identify your package as specific to
Django, and a corresponding django_
prefix for your module name. For
example, the django-ratelimit
package contains the
django_ratelimit
module.
Las etiquetas de la aplicación (es decir, la parte final del camino punteado a los paquetes de las aplicaciones) deben ser únicas en INSTALLED_APPS
. Evite utilizar la misma etiqueta como las de cualquier paquete contrib de Django:, por ejemplo, auth
, admin
, o messages
.
Move the polls
directory into django-polls
directory, and rename it
to django_polls
.
Edit django_polls/apps.py
so that name
refers to the
new module name and add label
to give a short name for
the app:
django-polls/django_polls/apps.py
¶from django.apps import AppConfig
class PollsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "django_polls"
label = "polls"
Cree un archivo django-polls/README.rst
con el siguiente contenido:
django-polls/README.rst
¶============
django-polls
============
django-polls is a Django app to conduct web-based polls. For each
question, visitors can choose between a fixed number of answers.
Detailed documentation is in the "docs" directory.
Quick start
-----------
1. Add "polls" to your INSTALLED_APPS setting like this::
INSTALLED_APPS = [
...,
"django_polls",
]
2. Include the polls URLconf in your project urls.py like this::
path("polls/", include("django_polls.urls")),
3. Run ``python manage.py migrate`` to create the models.
4. Start the development server and visit the admin to create a poll.
5. Visit the ``/polls/`` URL to participate in the poll.
Cree un archivo django-polls/LICENSE
. Elegir una licencia está fuera del alcance de este tutorial, pero basta con señalar que el código liberado públicamente sin ninguna licencia es inútil. Django y muchas aplicaciones compatibles con Django se distribuyen bajo la licencia BSD, sin embargo, usted es libre de elegir su propia licencia. Sólo tenga en cuenta que la elección de su licencia repercutirá sobre quién podrá utilizar su código.
Next we’ll create the pyproject.toml
file which details how to build and
install the app. A full explanation of this file is beyond the scope of this
tutorial, but the Python Packaging User Guide has a good
explanation. Create the django-polls/pyproject.toml
file with the
following contents:
django-polls/pyproject.toml
¶[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "django-polls"
version = "0.1"
dependencies = [
"django>=X.Y", # Replace "X.Y" as appropriate
]
description = "A Django app to conduct web-based polls."
readme = "README.rst"
requires-python = ">= 3.10"
authors = [
{name = "Your Name", email = "yourname@example.com"},
]
classifiers = [
"Environment :: Web Environment",
"Framework :: Django",
"Framework :: Django :: X.Y", # Replace "X.Y" as appropriate
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
]
[project.urls]
Homepage = "https://www.example.com/"
Many common files and Python modules and packages are included in the
package by default. To include additional files, we’ll need to create a
MANIFEST.in
file. To include the templates and static files, create a
file django-polls/MANIFEST.in
with the following contents:
django-polls/MANIFEST.in
¶recursive-include django_polls/static *
recursive-include django_polls/templates *
It’s optional, but recommended, to include detailed documentation with your
app. Create an empty directory django-polls/docs
for future
documentation.
Tenga en cuenta que el directorio docs
no se incluirá en su paquete a menos que usted agregue algunos archivos a este. Muchas aplicaciones Django proporcionan también su documentación online a través de sitios como readthedocs.org.
Many Python projects, including Django and Python itself, use Sphinx to build
their documentation. If you choose to use Sphinx you can link back to the
Django documentation by configuring Intersphinx
and including a value for Django in your project’s intersphinx_mapping
value:
intersphinx_mapping = {
# ...
"django": (
"https://docs.djangoproject.com/en/stable/",
None,
),
}
With that in place, you can then cross-link to specific entries, in the
same way as in the Django docs, such as
«:attr:`django.test.TransactionTestCase.databases`
».
Check that the build package is installed (python -m pip install
build
) and try building your package by running python -m build
inside
django-polls
. This creates a directory called dist
and builds your
new package into source and binary formats, django-polls-0.1.tar.gz
and
django_polls-0.1-py3-none-any.whl
.
For more information on packaging, see Python’s Tutorial on Packaging and Distributing Projects.
Dado que movimos el directorio polls
fuera del proyecto, ya no funciona. Vamos a solucionar esto mediante la instalación de nuestro nuevo paquete django-polls
.
Instalando como una librería de usuario
Los siguientes pasos instalan django-polls
como una librería de usuario. La instalación a nivel de usuario tiene muchas ventajas con respecto a instalar el paquete a nivel de sistema, como poder ser usado en sistemas donde no se tiene acceso de administrador así como impedir que el paquete afecte servicios del sistema y a otros usuarios del ordenador.
Note that per-user installations can still affect the behavior of system tools that run as that user, so using a virtual environment is a more robust solution (see below).
To install the package, use pip (you already installed it, right?):
python -m pip install --user django-polls/dist/django-polls-0.1.tar.gz
Update mysite/settings.py
to point to the new module name:
INSTALLED_APPS = [
"django_polls.apps.PollsConfig",
...,
]
Update mysite/urls.py
to point to the new module name:
urlpatterns = [
path("polls/", include("django_polls.urls")),
...,
]
Run the development server to confirm the project continues to work.
Ahora que hemos empaquetado y probado django-polls
, está lista para compartir con el mundo! Si esto no era más que un ejemplo, usted ahora podría:
Enviar por correo electrónico el paquete a un amigo.
Cargar el paquete en su sitio web.
Post the package on a public repository, such as the Python Package Index (PyPI). packaging.python.org has a good tutorial for doing this.
Earlier, we installed django-polls
as a user library. This has some
disadvantages:
Modificar las librerías de usuario puede afectar a otro programa Python en su sistema.
Usted no podrá ejecutar distintas versiones de este paquete (u otros con el mismo nombre).
Typically, these situations only arise once you’re maintaining several Django projects. When they do, the best solution is to use venv. This tool allows you to maintain multiple isolated Python environments, each with its own copy of the libraries and package namespace.
may 07, 2025