This was initially written as a reminder list of packages for myself and not intended as a blog but got later converted into one because why not.
It is not uncommon while designing codebase for your Django Application you run into a problem about solving trivial problems like debugging, protecting unauthenticated routes from script attacks, creating model diagrams , adding PWA to your website, Processing Images on the fly or adding a REST API into your project.
If you are familiar with Django's Philosophy of Loose Coupling and Tight Cohesion inside MVT and extensibility using packages it is no doubt it is one of the top choices while designing a web application in python.
This motive of this guide is to provide you some packages that I found pretty useful for my regular projects and workhorse helpers in my most used Django Codebase. Some of them are just plug and play while some other require extra attention while installing
1. Django Debug Toolbar
As the name itself suggests it is debug toolbar, but the great thing about this is how it sits tightly in the corner as helper and springs up when required.
The way to integrate it in your codebase is also very easy.
pip install django-debug-toolbar
Also in your settings.py
add after INSTALLED_APPS
, INTERNAL_IPS
generally are for the system ip if you aren't using it on localhost then change the INTERNAL_IPS
to your required one.
MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ]
INSTALLED_APPS += ['debug_toolbar', ]
DEBUG_TOOLBAR_CONFIG = {
'DISABLE_PANELS': ['debug_toolbar.panels.redirects.RedirectsPanel', ],
'SHOW_TEMPLATE_CONTEXT': True,
}
INTERNAL_IPS = ['127.0.0.1', 'localhost']
In your root urls.py
don't forget to add the following lines too. it is good practice to have debug toolbar only while debugging is true and not while in production.
from django.conf import settings
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
path('__debug__/', include(debug_toolbar.urls)),
]
Once done you would get the Debug Toolbar like this hovering over internal ips on right side.
Though there can be a whole blog about djdt but i leave it upon reader to checkout it's other cool features.
2. Django Recaptcha
It is not uncommon for developers to worry about unauthenticated forms to be penalised by script attacks and devising your own method for stopping such thing is itself a heavy task, Django Recaptcha really soves this quickly integrating with forms you need protection at.
pip install django-recaptcha
In your settings.py
add these few lines and for getting the keys visit Recaptcha Admin Console Panel , while generating keys choose a V3 Project it removes the checkbox in the form and doesn't come in way of valid users.
INSTALLED_APPS += ['captcha', ]
RECAPTCHA_PUBLIC_KEY = '<PUBLIC-KEY-HERE>'
RECAPTCHA_PRIVATE_KEY = '<PRIVATE-KEY-HERE>'
In your forms.py
Imports following
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV3
In forms.py
add this to your necessary form object and mention captcha
fields meta of the Form Object.
captcha = ReCaptchaField(
label='',
widget=ReCaptchaV3(
attrs={
'required_score': 0.75,
}
)
)
Now you have necessary protection on your django forms and one less problem to worry about. Below is how it will be viewable once your form is rendered on screen.
3. Django Extensions
Django Extensions is itself a pretty a big collection of really nice packages and has many tools that speed up your development process. Django Extension Documentation
pip install django-extensions
in your settings.py
add it this way.
INSTALLED_APPS += ['django_extensions', ]
The following are the tools added to manage.py
once it successfully installed
My Favorite among them is django model graph generator for that
pip install pygraphviz
python manage.py graph_models -a -g -o my_project_visualized.png
the result was neat model graph automatically generated from django models of a recent project of mine.
4 Django PWA
Normally you expect this to be a feature not of Server Side Application but at the end of day whichever framework generates the files necessary for PWA creation it really doesn't matter what created those files a server-side module or frontend framework like React.
The upsides , your application is downloadable as an application on mobile and you get real estate on menu of user's mobile screen but downside of implementation is not really much you can do if the users offline except showing a standard html page whcih informs about this or you can even host your mini js for users to fiddle with while they are offline and on your application.
I have implemented it in my personal website shreshtharora.com you can visit it for yourself and it works like butter.
Let's get started with process
pip install django-pwa
Add pwa to INSTALLED_APPS
in settings.py
INSTALLED_APPS = [
...
'pwa',
...
]
Define STATICFILES_DIRS
Directory
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
Configure the below Variables in settings.py
only
WA_APP_NAME = 'Application Name'
PWA_APP_DESCRIPTION = "Small Description about the Applicaion"
PWA_APP_THEME_COLOR = '#0A0302'
PWA_APP_BACKGROUND_COLOR = '#ffffff'
PWA_APP_DISPLAY = 'standalone'
PWA_APP_SCOPE = '/'
PWA_APP_ORIENTATION = 'any'
PWA_APP_START_URL = '/'
PWA_APP_STATUS_BAR_COLOR = 'default'
PWA_APP_ICONS = [
{
'src': '/static/my_app_icon.png',
'sizes': '160x160'
}
]
PWA_APP_ICONS_APPLE = [
{
'src': '/static/my_apple_icon.png',
'sizes': '160x160'
}
]
PWA_APP_SPLASH_SCREEN = [
{
'src': '/static/splash-640x1136.png',
'media': '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)'
}
]
PWA_APP_DIR = 'ltr'
PWA_APP_LANG = 'en-US'
Also don't forget to add urls of the package to the root urls.py
from django.urls import url, include
urlpatterns += [
url('', include('pwa.urls')), # Empty String is must for prefix
]
Add this to your base template or your empty templates for effective loading
{% load pwa %}
<head>
...
{% progressive_web_app_meta %}
...
</head>
The Above more detailed guide for PWA can be found in the Django PWA Repository
5. Django Imagekit
How many times we find ourselves with Images not being necessary sizes and need to resize them on fly or sometimes the users uploads a huge image file which would reduce load times of webpage. This is a pretty common problem and django-imagekit
is to the rescue
Install it in your pip
pip install django-imagekit
Add it to your installed Applications
INSTALLED_APPS = [
...
'imagekit',
...
]
Now it is ready to be used there are majorly two ways to call it one as a django model attribute or a directly by referencing it in templates
- Django Model Method
from django.db import models
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
class Profile(models.Model):
avatar = models.ImageField(upload_to='avatars')
avatar_thumbnail = ImageSpecField(source='avatar',
processors=[ResizeToFill(100, 50)],
format='JPEG',
options={'quality': 60})
Now there avatar_thumbnail
is generated and stored in CACHE
folder of media directory and auto handles the generation of the image as it is connected to avatar
field.
Also ImageSpecField
is just one of the many processors that come in box with Image Kit and custom image processors can be written using Pillow
Library and can be directly called.
Use Profile.avatar_thumbail
in template as you would any imageField object in Django
- Template Method
This method is more on the fly mechanism of converting images to necessary size requirements , it doesn't generate the image until the view is called but model method creates it as soon as the object ImageField is changed or added.
{% load imagekit %}
....
{% generateimage 'myapp:thumbnail' source=source_file %}
...
converts to
<img src="/media/CACHE/images/982d5af84cddddfd0fbf70892b4431e4.jpg" width="100" height="50" />
You can look up finer details in the official Documentation of django-imagekit for finer control over this.
6 Django Sentry
(Brownie for reaching till here) π
Sentry is an awesome service which my team at engineering logbook uses regularly for checking up where we effed up in production . π
Not the wisest choices. But Sentry
is our sword to kill those bugs that haunt us.
It has its own dashboard and a paid service after 30 days of trial though ( No Sponsorship from them though π’)
Process of Integrating them in your django website:
pip install --upgrade sentry-sdk
Below Code goes in settings.py
get dsn link from sentry.io
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
sentry_sdk.init(
dsn="<inter-your-dsn-link-here>",
integrations=[DjangoIntegration()],
# Set traces_sample_rate to 1.0 to capture 100%
# of transactions for performance monitoring.
# It is recommend adjusting this value in production,
traces_sample_rate=1.0,
# 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
)
More Details about the Sentry Package are available at Sentry Django Docs
Some More Ideas
I was hoping to go on adding details about Django REST API and Django GraphQL but they are enter series of blog posts about how to create, maintain and test them. so hopefully these packages will get their own entire blog posts that they deserve.
If you have any suggestions recommendations or ideas feel free to email on hey@shreshtharora.com or Contact me on twitter @AroraShreshth