Advanced tutorial: How to write reusable apps | Django documentation (2024)

This advanced tutorial begins where Tutorial 8left off. We’ll be turning our web-poll into a standalone Python packageyou can reuse in new projects and share with other people.

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

Reusability matters

It’s a lot of work to design, build, test and maintain a web application. ManyPython and Django projects share common problems. Wouldn’t it be great if wecould 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 ownPython programs. Check out Django Packages forexisting reusable apps you could incorporate in your project. Django itself isalso a normal Python package. This means that you can take existing Pythonpackages or Django apps and compose them into your own web project. You onlyneed 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 onewe’ve been working on. How do you make this app reusable? Luckily, you’re wellon the way already. In Tutorial 1, we saw how wecould decouple polls from the project-level URLconf using an include.In this tutorial, we’ll take further steps to make the app easy to use in newprojects and ready to publish for others to install and use.

Package? App?

A Python package provides a way of grouping related Python code foreasy reuse. A package contains one or more files of Python code (also knownas “modules”).

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

A Django application is a Python package that is specifically intendedfor use in a Django project. An application may use common Djangoconventions, such as having models, tests, urls, and viewssubmodules.

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

Your project and your reusable app

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

mysite/ 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 mysite/templates in Tutorial 7,and polls/templates in Tutorial 3. Now perhapsit is clearer why we chose to have separate template directories for theproject and application: everything that is part of the polls application is inpolls. It makes the application self-contained and easier to drop into anew project.

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

Installing some prerequisites

The current state of Python packaging is a bit muddled with various tools. Forthis tutorial, we’re going to use setuptools to build our package. It’sthe recommended packaging tool (merged with the distribute fork). We’llalso be using pip to install and uninstall it. You should install thesetwo packages now. If you need help, you can refer to how to installDjango with pip. You can install setuptoolsthe same way.

Packaging your app

Python packaging refers to preparing your app in a specific format that canbe easily installed and used. Django itself is packaged very much likethis. For a small app like polls, this process isn’t too difficult.

  1. First, create a parent directory for the package, outside of your Djangoproject. Call this directory django-polls.

    Choosing a name for your app

    When choosing a name for your package, check PyPI to avoid namingconflicts with existing packages. We recommend using a django-prefix for package names, to identify your package as specific toDjango, and a corresponding django_ prefix for your module name. Forexample, the django-ratelimit package contains thedjango_ratelimit module.

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

  2. Move the polls directory into django-polls directory, and rename itto django_polls.

  3. Edit django_polls/apps.py so that name refers to thenew module name and add label to give a short name forthe app:

    django-polls/django_polls/apps.py

    from django.apps import AppConfigclass PollsConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "django_polls" label = "polls"
  4. Create a file django-polls/README.rst with the following contents:

    django-polls/README.rst

    ============django-polls============django-polls is a Django app to conduct web-based polls. For eachquestion, 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.
  5. Create a django-polls/LICENSE file. Choosing a license is beyond thescope of this tutorial, but suffice it to say that code released publiclywithout a license is useless. Django and many Django-compatible apps aredistributed under the BSD license; however, you’re free to pick your ownlicense. Just be aware that your licensing choice will affect who is ableto use your code.

  6. Next we’ll create pyproject.toml, setup.cfg, and setup.py fileswhich detail how to build and install the app. A full explanation of thesefiles is beyond the scope of this tutorial, but the setuptoolsdocumentation has a goodexplanation. Create the django-polls/pyproject.toml,django-polls/setup.cfg, and django-polls/setup.py files with thefollowing contents:

    django-polls/pyproject.toml

    [build-system]requires = ['setuptools>=40.8.0']build-backend = 'setuptools.build_meta'

    django-polls/setup.cfg

    [metadata]name = django-pollsversion = 0.1description = A Django app to conduct web-based polls.long_description = file: README.rsturl = https://www.example.com/author = Your Nameauthor_email = yourname@example.comlicense = BSD-3-Clause # Example licenseclassifiers = 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 Topic :: Internet :: WWW/HTTP Topic :: Internet :: WWW/HTTP :: Dynamic Content[options]include_package_data = truepackages = find:python_requires = >=3.10install_requires = Django >= X.Y # Replace "X.Y" as appropriate

    django-polls/setup.py

    from setuptools import setupsetup()
  7. Only Python modules and packages are included in the package by default. Toinclude additional files, we’ll need to create a MANIFEST.in file. Thesetuptools docs referred to in the previous step discuss this file inmore detail. To include the templates, the README.rst and ourLICENSE file, create a file django-polls/MANIFEST.in with thefollowing contents:

    django-polls/MANIFEST.in

    include LICENSEinclude README.rstrecursive-include django_polls/static *recursive-include django_polls/templates *
  8. It’s optional, but recommended, to include detailed documentation with yourapp. Create an empty directory django-polls/docs for futuredocumentation. Add an additional line to django-polls/MANIFEST.in:

    recursive-include docs *

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

  9. Try building your package by running python setup.py sdist insidedjango-polls. This creates a directory called dist and builds yournew package, django-polls-0.1.tar.gz.

For more information on packaging, see Python’s Tutorial on Packaging andDistributing Projects.

Using your own package

Since we moved the polls directory out of the project, it’s no longerworking. 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-userinstalls have a lot of advantages over installing the package system-wide,such as being usable on systems where you don’t have administrator accessas well as preventing the package from affecting system services and otherusers of the machine.

Note that per-user installations can still affect the behavior of systemtools that run as that user, so using a virtual environment is a more robustsolution (see below).

  1. 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
  2. Update mysite/settings.py to point to the new module name:

    INSTALLED_APPS = [ "django_polls.apps.PollsConfig", ...,]
  3. Update mysite/urls.py to point to the new module name:

    urlpatterns = [ path("polls/", include("django_polls.urls")), ...,]
  4. Run the development server to confirm the project continues to work.

Publishing your app

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

Installing Python packages with a virtual environment

Earlier, we installed django-polls as a user library. This has somedisadvantages:

  • Modifying the user libraries can affect other Python software on your system.
  • You won’t be able to run multiple versions of this package (or others withthe same name).

Typically, these situations only arise once you’re maintaining several Djangoprojects. When they do, the best solution is to use venv. This tool allows you to maintain multiple isolatedPython environments, each with its own copy of the libraries and packagenamespace.

Advanced tutorial: How to write reusable apps | Django documentation (2024)

References

Top Articles
Latest Posts
Article information

Author: Arielle Torp

Last Updated:

Views: 6657

Rating: 4 / 5 (41 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Arielle Torp

Birthday: 1997-09-20

Address: 87313 Erdman Vista, North Dustinborough, WA 37563

Phone: +97216742823598

Job: Central Technology Officer

Hobby: Taekwondo, Macrame, Foreign language learning, Kite flying, Cooking, Skiing, Computer programming

Introduction: My name is Arielle Torp, I am a comfortable, kind, zealous, lovely, jolly, colorful, adventurous person who loves writing and wants to share my knowledge and understanding with you.