12 Hidden Gem Django Libraries You Should Know About! [PART 2]

This is part 2 of “12 Hidden Gem Django Libraries You Should Know About”. If you didn’t check the part 1 you can read it by clicking below…

12 Hidden Gem Django Libraries You Should Know About! [PART 2]
Photo by Milad Fakurian on Unsplash

This is part 2 of “12 Hidden Gem Django Libraries You Should Know About”. If you didn’t check the part 1 you can read it by clicking below link.

12 Hidden Gem Django Libraries You Should Know About! [PART 1]
Django is packed with built-in features, but third-party libraries can take your development to the next level. Here…

In this article, again we’ll explore 12 hidden gem Django libraries that can save you time, improve performance, and add powerful features to your projects.


1. django-hint: Type Hints for Django

Why You Need It: Adds type hints for Django models, views, and forms, improving code quality and catching errors early.
https://pypi.org/project/django-hint/0.1.2/

🔹 Installation:

pip install django-hint

🔹 Example:

from django_hint import QuerySet 
from .models import User 
 
def get_users() -> QuerySet[User]:  # Type hinting for QuerySet 
    return User.objects.all()

2. django-filter: Easy Filtering for QuerySets

Why You Need It: Quickly filter Django QuerySets without writing tons of boilerplate code.
https://pypi.org/project/django-filter/

🔹 Installation:

pip install django-filter

🔹 Example:

# settings.py 
INSTALLED_APPS = [ 
    ... 
    'django_filters', 
] 
 
# filters.py 
import django_filters 
from .models import Product 
 
class ProductFilter(django_filters.FilterSet): 
    """ 
    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 have a  
    filterset for it with the code: 
    """ 
    class Meta: 
        model = Product 
        fields = ['name', 'price', 'manufacturer'] 
 
# views.py 
from .filters import ProductFilter 
from .models import Product 
def product_list(request): 
    produc_filter = ProductFilter(request.GET, queryset=Product.objects.all()) 
    return render(request, 'my_app/template.html', {'filter': produc_filter})

3. django-seed: Generate Dummy Data

Why You Need It: Populate your database with random test data easily.
https://pypi.org/project/django-seed/

🔹 Installation:

pip install django-seed

🔹 Example:

# settings.py 
INSTALLED_APPS = [ 
    ... 
    'django_seed', 
]

Using with command

With django-seed, you can seed your database with test data from the command line using the manage.py seed command.

$ python manage.py seed api --number=15

This will seed 15 of each model for the app api.

Using with code

django-seed provides methods to easily seed test databases for your Django models. To seed your database with Model instances, import Seed, get a seeder instance, and use the add_entity method.

from django_seed import Seed 
from .models import Game, Player 
 
seeder = Seed.seeder() 
 
seeder.add_entity(Game, 5) 
seeder.add_entity(Player, 10) 
 
inserted_pks = seeder.execute()

This will seed 5 Game and 10 Player objects:

4. django-silk: Profiling & Performance Monitoring

source
Why You Need It: Profile database queries and API performance to optimize your app.
https://github.com/jazzband/django-silk

🔹 Installation:

pip install django-silk

🔹 Example:

# settings.py 
INSTALLED_APPS = [ 
    ... 
    'silk' 
] 
 
MIDDLEWARE = [ 
    ... 
    'silk.middleware.SilkyMiddleware', 
    ... 
] 
 
# urls.py 
urlpatterns += [ 
    path('silk/', include('silk.urls', namespace='silk')) 
]
python manage.py migrate

Silk will automatically begin interception of requests and you can proceed to add profiling if required. The UI can be reached at http:127.0.0.1/8000/silk/

5. django-cachalot: Automatic Query Caching

Why You Need It: Speed up your Django queries by caching them automatically.
https://django-cachalot.readthedocs.io/en/latest/

🔹 Installation:

pip install django-cachalot

🔹 Example:

# settings.py 
INSTALLED_APPS = [ 
    "cachalot" 
] 
 
CACHALOT_ENABLED = True # Enable caching 
 
CACHALOT_TIMEOUT = 300 # Number of seconds during which the cache should consider data as valid. None means an infinite timeout.

6. django-money: Handle Currency Fields Easily

Why You Need It: Add currency-aware fields to your models.
https://pypi.org/project/django-money/

🔹 Installation:

pip install django-money

🔹 Example:

# settings.py 
INSTALLED_APPS = [ 
   ..., 
   'djmoney', 
   ... 
] 
 
# models.py 
from djmoney.models.fields import MoneyField 
from django.db import models 
 
class BankAccount(models.Model): 
    balance = MoneyField(max_digits=14, decimal_places=2, default_currency='USD')
from djmoney.money import Money 
from .models import BankAccount 
 
account = BankAccount.objects.create(balance=Money(10, 'USD')) 
swissAccount = BankAccount.objects.create(balance=Money(10, 'CHF')) 
 
BankAccount.objects.filter(balance__gt=Money(1, 'USD')) 
# Returns the "account" object

7. django-countries: Handle Country Fields Easily

Why You Need It: Provides country choices for use with forms, flag icons static files, and a country field for models.
https://github.com/SmileyChris/django-countries

👉 Checkout a detailed video of django-countries on my youtube channel

🔹 Installation:

pip install django-countries

🔹 Example:

# settings.py 
INSTALLED_APPS = [ 
   ..., 
   'django_countries', 
   ... 
] 
 
# models.py 
from django.db import models 
from django_countries.fields import CountryField 
 
class Person(models.Model): 
    name = models.CharField(max_length=100) 
    country = CountryField()
>>> from myapp.models import Person 
>>> person = Person(name="Chris", country="NZ") 
>>> person.country 
Country(code='NZ') 
>>> person.country.name 
'New Zealand' 
>>> person.country.flag 
'/static/flags/nz.gif'

8. django-colorfield: Handle Color Fields Easily

source
Why You Need It: simple color field for your models with a nice color-picker in the admin-interface.
https://pypi.org/project/django-colorfield/

👉 Checkout a detailed video of django-colorfield on my youtube channel

🔹 Installation:

pip install django-colorfield

🔹 Example:

# settings.py 
INSTALLED_APPS = [ 
   ..., 
   'django_countries', 
   ... 
] 
 
# models.py 
from colorfield.fields import ColorField 
from django.db import models 
 
class MyModel(models.Model): 
    color = ColorField(default='#FF0000')

9. django-health-check: Monitor Your App’s Health

Why You Need It: Provides real-time health checks for databases, caches, and queues.
https://pypi.org/project/django-health-check/

🔹 Installation:

pip install django-health-check

🔹 Example:

INSTALLED_APPS = [ 
        # ... 
        'health_check',                             # required 
        'health_check.db',                          # stock Django health checkers 
        'health_check.cache', 
        'health_check.storage', 
        'health_check.contrib.migrations', 
        'health_check.contrib.celery',              # requires celery 
        'health_check.contrib.celery_ping',         # requires celery 
        'health_check.contrib.psutil',              # disk and memory utilization; requires psutil 
        'health_check.contrib.s3boto3_storage',     # requires boto3 and S3BotoStorage backend 
        'health_check.contrib.rabbitmq',            # requires RabbitMQ broker 
        'health_check.contrib.redis',               # requires Redis broker 
    ] 
 
# urls.py 
urlpatterns = [ 
    # ... 
    path(r'ht/', include('health_check.urls')), 
]

📌 Visit http:127.0.0.1/8000/ht/ to see the health status!

10. django-anymail: Send Emails via Mailgun, SendGrid, SES, etc.

Why You Need It: Provides email backend support for multiple services.
https://anymail.dev/en/stable/

🔹 Installation:

pip install django-anymail

🔹 Example:

# settings.py 
INSTALLED_APPS = [ 
    "anymail", 
] 
 
# Settings for Mailgun: 
ANYMAIL = { 
    # (exact settings here depend on your ESP...) 
    "MAILGUN_API_KEY": "<your Mailgun key>", 
    "MAILGUN_SENDER_DOMAIN": 'mg.example.com',  # your Mailgun domain, if needed 
} 
EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" 
DEFAULT_FROM_EMAIL = "you@example.com"  # if you don't already have this in settings 
SERVER_EMAIL = "your-server@example.com"  # ditto (default from-email for Django errors) 
 
# urls.py 
from django.urls import include, path 
 
urlpatterns = [ 
    ... 
    path("anymail/", include("anymail.urls")), 
] 
 
# views.py 
from django.core.mail import send_mail 
 
send_mail("It works!", "This will get sent through Mailgun", 
          "Anymail Sender <from@example.com>", ["to@example.com"])

11. django-webpack-loader: Integrate Webpack with Django

Why You Need It: Helps manage frontend assets with Webpack inside Django projects.
https://github.com/django-webpack/django-webpack-loader

🔹 Installation:

npm install --save-dev webpack-bundle-tracker 
 
pip install django-webpack-loader

🔹 Configuration:

Before configuring django-webpack-loader, let's first configure what's necessary on webpack-bundle-tracker side. Update your Webpack configuration file (it's usually on webpack.config.js in the project root). Make sure your file looks like this (adapt to your needs):

const path = require("path"); 
const webpack = require("webpack"); 
const BundleTracker = require("webpack-bundle-tracker"); 
 
module.exports = { 
  context: __dirname, 
  entry: "./assets/js/index", 
  output: { 
    path: path.resolve(__dirname, "assets/webpack_bundles/"), 
    publicPath: "auto", // necessary for CDNs/S3/blob storages 
    filename: "[name]-[contenthash].js", 
  }, 
  plugins: [ 
    new BundleTracker({ path: __dirname, filename: "webpack-stats.json" }), 
  ], 
};

🔹 Example:

# settings.py 
INSTALLED_APPS = [ 
    ... 
    'webpack_loader', 
    ... 
] 
 
STATICFILES_DIRS = ( 
    os.path.join(BASE_DIR, 'assets'), 
) 
 
WEBPACK_LOADER = { 
    'DEFAULT': { 
        'BUNDLE_DIR_NAME': 'webpack_bundles/', 
        'CACHE': not DEBUG, 
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), 
        'POLL_INTERVAL': 0.1, 
        'IGNORE': [r'.+\.hot-update.js', r'.+\.map'], 
    } 
}

In development, we can simply do:

# in one shell 
npx webpack --mode=development --watch 
 
# in another shell 
python manage.py runserver

Below is the basic usage for render_bundle within a template:

{% load render_bundle from webpack_loader %} 
 
<html> 
  <head> 
    {% render_bundle 'main' 'css' %} 
  </head> 
</html>

That will render the proper <script> and <link> tags needed in your template.

12. django-auto-prefetch: Reduce N+1 Query Problems Automatically

Why You Need It: Prevents N+1 query issues by automatically prefetching related objects in Django ORM queries.
https://github.com/tolomea/django-auto-prefetch

🔹 Installation:

pip install django-auto-prefetch

🔹 Example:

if you had you model:

from django.db import models 
 
 
class Book(models.Model): 
    author = models.ForeignKey("Author", on_delete=models.CASCADE) 
 
    class Meta: 
        verbose_name = "Book"

…swap to this:

import auto_prefetch 
from django.db import models 
 
 
class Book(auto_prefetch.Model): 
    author = auto_prefetch.ForeignKey("Author", on_delete=models.CASCADE) 
 
    class Meta(auto_prefetch.Model.Meta): 
        verbose_name = "Book"

🚀 Conclusion

These 12 additional hidden gem Django libraries bring even more power and flexibility to your projects. Whether you need better caching, email integration, performance monitoring, these libraries will make your life easier!

👉 Which one is your favorite? Let me know in the comments! 🚀🔥


If you haven’t check the part 1, please check this now:

12 Hidden Gem Django Libraries You Should Know About! [PART 1]
Django is packed with built-in features, but third-party libraries can take your development to the next level. Here…