The Django web framework consists of multiple modules or packages that allow developers to quickly write the application without having to engineer an app's backend from scratch. Django is considered a full-stack web framework because it combines a database, application server, template engine, authentication modules and dispatcher to create a high-level framework.

In this article we'll review the top 8 most-used Django packages in the industry. These packages can assist with REST APIs, views, forms, debug tools, data relationships, and more.

1. Django-rest-framework

Django-rest-framework is one of the best packages for creating APIs with Django. Django-rest-framework integrates well with other Django-filters to reuse the filters you have created for model listing in your REST APIs.

The most important features of this package are:

  • It includes authentication policies for OAuth1 and OAuth2.
  • Serialization that supports both ORM and non-ORM data sources.
  • It is easily customizable all the way down. It simply uses a regular function-based view if you don’t need the more powerful features.
  • It has very good documentation.

Django-rest-framework Installation

Note: Install pip (a package manager for python packages) before package installation.

pip install djangorestframework

Add rest_framework to your INSTALLED_APPS setting:

INSTALLED_APPS = [
    ...
    'rest_framework',
]

Start up a new project:

pip install django
pip install djangorestframework
django-admin startproject example .
./manage.py migrate
./manage.py createsuperuser

Edit the example/urls.py module in your project:

from django.urls import path, include
from django.contrib.auth.models import User
from rest_framework import serializers, viewsets, routers

# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'is_staff']

# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

# Routers provide a way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Add the following to your settings.py module:

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

Finally, run manage.py:

./manage.py runserver	

Now, you can post and retrieve the users in curl commands

$ curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
[
    {
        "url": "http://127.0.0.1:8000/users/1/",
        "username": "admin",
        "email": "admin@example.com",
        "is_staff": true,
    }
]

2. Django-cors-headers

The Django-cors-headers package adds cross-origin resource sharing headers to responses. This allows in-browser requests to your Django application from other origins. Adding cross-origin headers can unintentionally open up your site's private data to others, so it's important to understand the implications of using this package.

Using this package, you can perform the following functionalities:

  • Regex matches for allowed origins
  • URL Regex for allowed URL
  • CORS allowed method like POST, PUT
  • CORS allowed headers

Django-cors-headers Installation

Install from PIP:

pip install django-cors-headers

Add it to your installed apps:

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]

You will also need to add a middleware class to listen to the responses:

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django CommonMiddleware.

CORS_ALLOWED_ORIGINS allows you to add the list of origins that are authorized to make cross-site HTTP requests.

CORS_ALLOWED_ORIGINS = [
    "https://example.com",
    "https://sub.example.com",
    "http://localhost:8080",
    "http://127.0.0.1:9000"
]

3. Django-debug-toolbar

This is a well-known package for debugging Django apps that is included in the development configuration of many projects. It has various panels that help you debug your application. The most useful is the one that displays all SQL queries that are executed for a page load.

Django-debug-toolbar Installation

Install from PIP:

pip install django-debug-toolbar

Add it to your installed apps:

[
# ...
'django.contrib.staticfiles',
# ...
'debug_toolbar',
]

Add the Debug Toolbars URL to your project's URLconf as below:

from django.conf import settings
from django.urls import include, path

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        path('__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns

Debug toolbar is usually implemented in a middleware. One should include the debug toolbar middleware as early as possible in the middleware list:

MIDDLEWARE = [
    # ...
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    # ...
]

4. Django-extensions

Django-extensions is one of the most useful packages that can be added to Django projects. It provides you with custom Django extensions like shell-plus, which automatically imports all the modules in your project. It has many useful commands like admin generator, run server plus, and validate templates. It basically is a set of tools that will help with your daily work.

Django command extension features are:

  • Export mails
  • Generate mails
  • Generate graph models
  • Create template tags for views
  • List the model info of the DB

Django-extensions Installation

Install from PIP:

pip install django-extensions

You need to add it to installed_apps in your project’s settings.py file:

INSTALLED_APPS = (
    ...
    'django_extensions',
    ...
)

Below are the commands to use different extensions:

Generate a graphviz graph of app models

python manage.py graph_models -a -o myapp_models.png

Check templates for rendering errors

python manage.py validate_templates

Produce a tab-separated list of tuples for a project

python manage.py show_urls

5. Sentry-sdk

Sentry-sdk is a must-have tool for any Django project, as it’s important that we stay informed about all the codebase-related issues in the application. The package immediately alerts us about all the previously-uncaught exceptions that occurred in production. We can catch the issue ourselves and send the error information to Sentry, along with additional data.

Building an alert system on our own is definitely non-trivial, and debugging without these kinds of logs is next to impossible. It will catch any uncaught exceptions and send us full details about the issues right after it happens.

Following are the main features of Sentry-sdk:

  • Act as global error handling mechanism
  • Act as alert system when some exception is caught

Sentry-sdk Installation

Install from PIP:

pip install --upgrade sentry-sdk	

Configure SDK in the project and initialize it with Django integration in your settings.py file:

import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
    integrations=[DjangoIntegration()],

    # If you wish to associate users to errors (assuming you are using
    # django.contrib.auth) you may enable sending PII data.
    send_default_pii=True
)

Below is a sample code to verify sentry installations by creating a route that riggers an error:

from django.urls import path

def trigger_error(request):
    division_by_zero = 1 / 0

urlpatterns = [
    path('sentry-debug/', trigger_error),
    # ...
]

6. Django-allauth

Django-allauth is a reusable Django app that allows for both local and social authentication. It supports multiple authentication schemes (e.g. login by user name or by e-mail), and multiple strategies for account verification (ranging from none to e-mail verification).

Moreover, all access tokens are consistently stored so that you can publish wall updates. It also has pluggable signup form for asking additional questions during signup and support for connecting multiple social accounts to a Django user account. It also provides the required consumer keys and secrets for interacting with Facebook, Twitter, and other platforms, to be configured in the database via Django admin using the SocialApp model.

Consumer keys and tokens make use of the Django sites framework. This is especially helpful for larger multi-domain projects, but also allows for easy switching between a development (localhost) and production setup without messing with your settings and database.

Django-allauth supported features:

  • Signup of both, local and social accounts
  • Connecting more than one social account to a local account
  • E-mail address management like setting up multiple e-mail addresses, creating a primary address, and more
  • Forgot Password flow
  • E-mail address verification flow

Django-allauth Installation

Install from PIP:

pip install django-allauth

Add the below code in setting.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # Already defined Django-related contexts here

                # `allauth` needs this from django
                'django.template.context_processors.request',
            ],
        },
    },
]

AUTHENTICATION_BACKENDS = [
    ...
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
    ...
]

INSTALLED_APPS = [
    ...
    # The following apps are required:
    'django.contrib.auth',
    'django.contrib.messages',
    'django.contrib.sites',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    # ... include the providers you want to enable:
    'allauth.socialaccount.providers.agave',
    'allauth.socialaccount.providers.amazon',
    ...
    ...
]

SITE_ID = 1

# Provider specific settings
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        # For each OAuth based provider, either add a ``SocialApp``
        # (``socialaccount`` app) containing the required client
        # credentials, or list them here:
        'APP': {
            'client_id': '123',
            'secret': '456',
            'key': ''
        }
    }
}

Update the url.py file to enable social authentication.

urlpatterns = [
    ...
    path('accounts/', include('allauth.urls')),
    ...
]

7. Django-filter

Django-filter is a generic, reusable application to spare you the effort of writing some of the more mundane bits of view code. It also allows users to filter down a queryset based on a model’s fields, displaying the form to let them do this.

Django-filter is tested against all supported versions of python and Django.

Django-filter Installation

Install from PIP:

pip install django-filter

Add django_filters in INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'django_filters',
]

Django-filter can be used for generating interfaces similar to the Django admin's list_filter interface. It has an API very similar to Django's ModelForms. For example, if you had a Product model, you could also have a filterset for it with the code:

import django_filters

class ProductFilter(django_filters.FilterSet):
    class Meta:
        model = Product
        fields = ['name', 'price', 'manufacturer']

Then, in your view, you could run the following command:

def product_list(request):
    filter = ProductFilter(request.GET, queryset=Product.objects.all())
    return render(request, 'my_app/template.html', {'filter': filter})

8. Django-import-export

Django-import-export is helpful in importing bulk data using Excel, CSV, JSON, and YAML files. It has built-in preview and admin support. You can also provide filters for exporting and ordering data.

Features:

  • support multiple formats (Excel, CSV, JSON)
  • admin integration for importing
  • preview import changes
  • admin integration for exporting
  • export data respecting admin filters

Django-import-export Installation

Install from PIP:

pip install django-import-export	

Change INSTALLED_APPS of setting.py:

INSTALLED_APPS = (
    ...
    'import_export',
)

Creating an import-export resource to integrate Django-import-export with our book model, we will create a ModelResource class in admin.py that will describe how this resource can be imported or exported:

# app/admin.py

from import_export import resources
from core.models import Book

class BookResource(resources.ModelResource):

    class Meta:
        model = Book

Exporting data:

>>> from app.admin import BookResource
>>> dataset = BookResource().export()
>>> print(dataset.csv)
id,name,author,author_email,imported,published,price,categories
2,Some book,1,,0,2012-12-05,8.85,1

Let the Top Open Source Django Packages Do the Work For You

These packages are reliable, commonly used open source packages in Django. The value of these packages can vary from use case to use case contingent on the situation and project.

Django is one of the most widely adopted, robust, versatile, and well-supported frameworks. The Crowdbotics App Builder uses Django to provide the backend for all generated applications, and Django is also our preferred backend framework for managed app builds.

If you are looking to build an application using Django, we recommend contacting one of Crowdbotics' experts for a comprehensive quote.