Advanced tutorial: How to write reusable apps

    If you haven’t recently completed Tutorials 1–7, we encourage you to review these so that your example project matches the one described below.

    It’s a lot of work to design, build, test and maintain a web application. Many Python and Django projects share common problems. Wouldn’t it be great if we could save some of this repeated work?

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

    Let’s say you were starting a new project that needed a polls app like the one we’ve been working on. How do you make this app reusable? Luckily, you’re well on the way already. In Tutorial 1, we saw how we could decouple polls from the project-level URLconf using an . In this tutorial, we’ll take further steps to make the app easy to use in new projects and ready to publish for others to install and use.

    Package? App?

    A Python provides a way of grouping related Python code for easy reuse. A package contains one or more files of Python code (also known as “modules”).

    A package can be imported with import foo.bar or from foo import bar. For a directory (like polls) to form a package, it must contain a special file __init__.py, even if this file is empty.

    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.

    Later on we use the term packaging to describe the process of making a Python package easy for others to install. It can be a little confusing, we know.

    Your project and your reusable app

    After the previous tutorials, our project should look like this:

    You created mysite/templates in , 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.

    The polls directory could now be copied into a new Django project and immediately reused. It’s not quite ready to be published though. For that, we need to package the app to make it easy for others to install.

    The current state of Python packaging is a bit muddled with various tools. For this tutorial, we’re going to use 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 . You can install setuptools the same way.

    Packaging your app

    1. First, create a parent directory for polls, outside of your Django project. Call this directory django-polls.

      Choosing a name for your app

      When choosing a name for your package, check resources like PyPI to avoid naming conflicts with existing packages. It’s often useful to prepend django- to your module name when creating a package to distribute. This helps others looking for Django apps identify your app as Django specific.

      Application labels (that is, the final part of the dotted path to application packages) must be unique in . Avoid using the same label as any of the Django contrib packages, for example auth, admin, or messages.

    2. Move the polls directory into the django-polls directory.

    3. Create a file django-polls/README.rst with the following contents:

      django-polls/README.rst

      1. =====
      2. Polls
      3. =====
      4. Polls is a Django app to conduct web-based polls. For each question,
      5. Detailed documentation is in the "docs" directory.
      6. Quick start
      7. 1. Add "polls" to your INSTALLED_APPS setting like this::
      8. INSTALLED_APPS = [
      9. ...
      10. 'polls',
      11. ]
      12. 2. Include the polls URLconf in your project urls.py like this::
      13. path('polls/', include('polls.urls')),
      14. 3. Run ``python manage.py migrate`` to create the polls models.
      15. 4. Start the development server and visit http://127.0.0.1:8000/admin/
      16. to create a poll (you'll need the Admin app enabled).
      17. 5. Visit http://127.0.0.1:8000/polls/ to participate in the poll.
    4. Create a django-polls/LICENSE file. Choosing a license is beyond the scope of this tutorial, but suffice it to say that code released publicly without a license is useless. Django and many Django-compatible apps are distributed under the BSD license; however, you’re free to pick your own license. Just be aware that your licensing choice will affect who is able to use your code.

    5. Next we’ll create pyproject.toml, setup.cfg, and setup.py files which detail how to build and install the app. A full explanation of these files is beyond the scope of this tutorial, but the has a good explanation. Create the django-polls/pyproject.toml, , and django-polls/setup.py files with the following contents:

      django-polls/pyproject.toml

      1. requires = ['setuptools>=40.8.0', 'wheel']
      2. build-backend = 'setuptools.build_meta:__legacy__'

      django-polls/setup.cfg

      django-polls/setup.py

      1. from setuptools import setup
      2. setup()
    6. Only Python modules and packages are included in the package by default. To include additional files, we’ll need to create a MANIFEST.in file. The setuptools docs referred to in the previous step discuss this file in more detail. To include the templates, the README.rst and our LICENSE file, create a file django-polls/MANIFEST.in with the following contents:

      1. include LICENSE
      2. include README.rst
      3. recursive-include polls/static *
      4. recursive-include polls/templates *
    7. It’s optional, but recommended, to include detailed documentation with your app. Create an empty directory django-polls/docs for future documentation. Add an additional line to django-polls/MANIFEST.in:

      Note that the docs directory won’t be included in your package unless you add some files to it. Many Django apps also provide their documentation online through sites like readthedocs.org.

    8. Try building your package with python setup.py sdist (run from inside django-polls). This creates a directory called dist and builds your new package, django-polls-0.1.tar.gz.

    For more information on packaging, see Python’s .

    Since we moved the polls directory out of the project, it’s no longer working. We’ll now fix this by installing our new django-polls package.

    Installing as a user library

    The following steps install django-polls as a user library. Per-user installs have a lot of advantages over installing the package system-wide, such as being usable on systems where you don’t have administrator access as well as preventing the package from affecting system services and other users of the machine.

    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).

    1. To install the package, use pip (you already installed it, right?):

      1. python -m pip install --user django-polls/dist/django-polls-0.1.tar.gz
    2. With luck, your Django project should now work correctly again. Run the server again to confirm this.

    3. To uninstall the package, use pip:

      1. python -m pip uninstall django-polls

    Publishing your app

    Now that we’ve packaged and tested django-polls, it’s ready to share with the world! If this wasn’t just an example, you could now:

    Earlier, we installed the polls app as a user library. This has some disadvantages:

    • You won’t be able to run multiple versions of this package (or others with the same name).