The typical modules and libraries to use in a Django project

Share your love

Are you thinking of starting a Django project, but you aren’t sure which additional libraries or packages you need?

Or maybe, searching for a solution on the internet that has an answer to a problem you are trying to solve. Do not code some functionalities from scratch; add additional third-party packages.

Some packages and libraries are essential when using Django to build a large site.

For example, if you are using Django to develop a blogging site, you should not miss out on the Django TinyMCE WYSIWYG HTML editor.

Pillow, Django crispy forms, Django rest framework, Django storages, TinyMCE, python decouple, and django-allauth are some libraries and packages you use to achieve additional functionality for your next Django project.

Who knows what you will be using for your next Django project. It all depends on the problem that you are trying to solve.

Have you ever experienced that moment when you just want to give up on your web or software development project? Like you really don’t know how to approach a problem.

Other times, tackling a project by taking the long road of coding it from scratch would take a vast amount of your time. Some projects take a hell of a time to complete, others mind-bog you, and others are just naturally huge.

Well, never overthink any of it. It’s just gonna bring additional problems. Approach each situation differently, and you will realize how easy programming is.

For me, I research. Most likely, in the vast universe, an earthling or spacely being has faced the same problem. I hope it is an R2-D2 robot from Star Wars, Ha!

Whatever intelligent being or robot, you will probably find a narrative on how they solved the problem or find the ultimate solution packaged in a library or a package. Whatever the answer is, that is what you will use to implement your idea into a web solution.

Easy Peasy! There is no wasting time trying to code a custom solution that would probably introduce bugs into your web application.

Just use that Library!

So, research is vital. Before you start typing any line of code, browse the internet and see what others are doing on that particular problem. It’s going to save you a tremendous amount of time and frustration.

And to lesser frustration, I provide you with the ultimate libraries and packages that I have used to enhance functionality and security for Django projects that I have done in the past, are doing, or possibly will do in the future.

Here is a list of all the packages and libraries that you will need for your next Django project

  1. Pillow
  2. Django crispy forms
  3. Django rest framework
  4. Django storages
  5. Django TinyMCE
  6. Python decouple
  7. Django allauth

#1. Pillow

Written in Python, Pillow is a Python Image processing library. The library manipulates and saves images uploaded in Django in a format or size of your liking. You can use Pillow to create thumbnails, convert them from one format to another (for example, from PNG to JPG), compress images, and enable printing.

How to install Pillow in your Django project

Here’s how to install Pillow and use it on your Django project.

Open the Terminal and activate the virtual environment for your Django project. Type the following command to install Pillow.

pip install pillow

No configuration is needed because Pillow as default is automatically added to the PYTHONPATH variable. You can work with the default settings.

Whenever you want to use it, import the library as follows:

from PIL import Image

How to use Pillow to compress images uploaded with Django

Here’s an example code that you can use to compress, change format, and resize images with Pillow for your uploaded images.

In your models.py, copy the code and tweak it according to your liking.

from io import BytesIO
from django.db import models
from django.core.files import File
from PIL import Image



class BlogPost(models.Model):
    title = models.CharField(max_length=80)
    post_image = models.ImageField(upload_to='blog/images')
    ...

    # compress the image and change the format to JPEG before saving it
    def save(self, *args, **kwargs):
        preprocessed_image = Image.open(self.post_image)
        preprocessed_image.save(BytesIO, 'JPEG', quality='70')
        processed_image = File(BytesIO, name=self.post_image.name)
        self.post_image = processed_image
        super().save(*args, **kwargs)

The code above opens an uploaded image submitted from a form, sets the format to JPEG, and compresses the image maintaining the quality at 70%. Your pictures will look as good as the original images. Besides, save on space.

More about Pillow library. Follow this link.

#2. Django Crispy Forms

Django Crispy Forms is a package that I never miss installing whenever I am starting on a new Django project. The package offers out-of-the-box functionality to style your forms without writing any styling code.

Django crispy forms work well with popular CSS frameworks such as Bootstrap (Version 2, 3, and 4), uni-form, foundation, and tailwind CSS.

How to install django-crispy-forms in your Python environment that has Django

Here’s how you can install Django Crispy Forms in your Django project:

Open the Terminal and activate the virtual environment that you have your Django installed. Type the following and press Enter.

pip install django-crispy-forms

After installing Django Cripsy Forms, edit your settings.py file and add crispy_forms inside the INSTALLED_APPS variable.

Your file should look like this:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',


    # 'home.apps.HomeConfig',
    'crispy_forms',
]

After activating the crispy_forms app, you should add a line of code at the end of your settings.py file to configure Django Crispy Forms to use your desired CSS framework.

For bootstrap, use the following line:

CRISPY_TEMPLATE_PACK = 'bootstrap4'

You can style your Django forms using uni-form by adding the following line:

CRISPY_TEMPLATE_PACK = 'uni_form'

After configuring the preferred CSS framework, use Django Cripsy Forms by adding the following lines in your templates.

At the top of your template file, add:

{% load crispy_forms_tags %}

Then use Crispy Forms tags in your Django form:

{{ form|crispy }}

#3. Django Rest Framework

One of the best toolkits you could use to create API endpoints for your Django project. APIs are essential for building web applications consumed across different devices and technologies.

For example, you would utilize APIs in your Django application to be consumed by web and mobile applications.

You do not have to create a new Android application to manipulate the same data created or updated in your Django application.

Django Rest Framework allows you to perform CRUD (Create, Read, Update, Delete) operations across different technologies and devices.

How to install Django Rest Framework

Open the Terminal and ensure you have activated the virtual environment that has Django installed. Type the following:

pip install djangorestframework

pip install markdown

pip install django-filter

After installation, add the rest_framework app to your installed apps.

INSTALLED_APPS = [
    
    ,,,

    'rest_framework',
]

#4. Django Storages

Whenever you host your web application live, you will need reliable file storage and a CDN delivery network such as Amazon s3. Django Storages comes into play by combining most of the custom storage backends for Django. These could be Amazon s3, Axure storage, Google Cloud Storage, Dropbox, FTP, Digital Ocean, e.t.c.

How to install and use Django Storages in your Django project

To install and use Django Storages, open a Terminal window with an activated virtual environment and execute the following command:

pip install django-storages 

I use Amazon S3 buckets to keep my Django files. Amazon S3 uses the S3Boto3Storage backend to process files uploaded through the web application.

Here’s how to use the Amazon S3 bucket in your Django project:

Upload media files to the S3 bucket by adding the following line in your main settings file

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

Whenever you run ‘python manage.py collectstatic’, you can configure the backend to automatically put the static files in your S3 bucket by adding the following line in settings.py:

STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'

Besides, if you are using the CloudFront CDN service, you can serve your S3 bucket files by adding the following lines in your settings.py file:

AWS_S3_CUSTOM_DOMAIN = 'cdn.mydomain.com'

AWS_CLOUDFRONT_KEY = os.environ.get('AWS_CLOUDFRONT_KEY', None).encode('ascii')

AWS_CLOUDFRONT_KEY_ID = os.environ.get('AWS_CLOUDFRONT_KEY_ID', None)

#5. Django TinyMCE

Do you like writing your thoughts out? Or maybe you have a goal of starting a new Django blog.

Using Django and TinyMCE together is a good combination for content creation, editing, and updating. Instead of styling every post, you add to your Django blog and format your content using Django TinyMCE editor.

What is TinyMCE used for?

Django TinyMCE is a rich text editor used to produce a visual editor when working with HTML text area fields or other HTML elements such as paragraphs, tables, e.t.c. TinyMCE allows you to edit your blog posts visually as you create them.

In addition, TinyMCE is easily integrated with Django, React, Vue, and other technologies. Therefore, if you use Django for backend purposes, you can easily integrate TinyMCE with a frontend framework such as React.

How to install Django TinyMCE

Install Django TinyMCE by opening a Terminal window and activating the virtual environment.

Next, type the following line to install TinyMCE

pip install django-tinymce

Then, add TinyMCE to your installed apps

INSTALLED_APPS = [
    
    'tinymce',
   
]

Additionally, add TinyMCE URLs to your main urls.py app

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('home.urls')),


    path('tinymce/', include('tinymce.urls')),
]

The good thing about TinyMCE is that you can customize it.

How to use and Customize TinyMCE in Django

You can add fonts, typography, and which elements to appear on the toolbar and menubar. Besides, you can install plugins that can add additional functionality to the text editor.

Here’s an example of a configuration that I find optimal whenever I am editing my posts:

TINYMCE_DEFAULT_CONFIG = {
    "language": "es_ES",
    "height": "320px",
    "width": "960px",

    "menubar": "file edit view insert format tools table help",
    "plugins": "advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code "
    "fullscreen insertdatetime media table paste code help wordcount spellchecker",
    "toolbar": "undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft "
    "aligncenter alignright alignjustify | outdent indent |  numlist bullist checklist | forecolor "
    "backcolor casechange permanentpen formatpainter removeformat | pagebreak | charmap emoticons | "
    "fullscreen  preview save print | insertfile image media pageembed template link anchor codesample | "
    "a11ycheck ltr rtl | showcomments addcomment code",
    "custom_undo_redo_levels": 10,
}

#6. Python Decouple

Security and access authorization are critical when it comes to the development of web applications. Although Django could be the best framework in terms of security, sometimes leaving some lines of code exposed could compromise your web application.

To avoid such compromise, you need the Python Decouple library to manage your secret keys, API endpoints, passwords, and other sensitive information added to the Django code.

Features that Python Decouple provide

Python Decouple allows you to:

  • Convert property values into a correct and consumable data type. Type conversion is essential for APIs when a valid data type is required to communicate with an endpoint. For example, you can specify an INT data type to be converted to STR before using it.
  • Store sensitive information and parameters in .env or files. However, you should be careful not to commit these files to a remote source such as GitHub or BitBucket. That way, your secret code is not exposed.

How to install Python Decouple in your Django Project

Open the Terminal and activate the virtual environment. Type the following:

pip install python-decouple

The PYTHONPATH variable automatically adds the ‘decouple’ value when you install Python Decouple. Therefore, after installation, you can start using it right away.

How to use Python Decouple to store Django secret values and passwords

Import the library at the top of your main settings file

from decouple import config

Create a new .env file in the directory where you have your main project files. In this case, it should be in the same folder as the manage.py file. Add your secret parameters and values the same way you do for variable: mypass=1234

Edit your .gitignore file to exclude your .env file from being committed to a remote repository. The final .gitignore file should have the following lines:

.env
*.env
.conf
.pem
.perm

After storing your secret keys in your .env files, retrieve and use them in your Django project as follows:

SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)

This way, you keep your secret information from the main Django code.

#7. Django-allauth

Finally, we have the Django-allauth authentication system.

What is Django-allauth, and how is it used in Django projects

Django-allauth is an integration of a set of Django applications that handle registration, account management, and authentication of users in your Django application. Besides, Django-allauth allows easy social account authentication. Therefore, you can use Gmail, Facebook, and Twitter to authenticate users when creating their accounts.

Advantages of using Django-allauth in your Django project

  1. Supports social authentication
  2. Adds the functionality of authenticating users using usernames or e-mails
  3. Improves signup rates as it is easier to create an account with your website without providing too much information
  4. The package offers enhanced security as it passes scans for most web vulnerabilities

How to install Django-allauth

Open the Terminal when you have your Django installed and type the following:

pip install django-allauth

In your settings.py file, ensure you have ‘django.contrib.sites’ added to your INSTALLED_APPS

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',

    # ensure you have these apps
    'django.contrib.auth',
    'django.contrib.messages',
    'django.contrib.sites',

    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.staticfiles',



    'home.apps.HomeConfig',
    'crispy_forms',
    'tinymce',
]

To add the providers that you want your users to use, add them to your installed apps. For example, to allow users to sign up using their Google account, add the following line to your setting.py file:

    'allauth',
    'allauth.account',
    'allauth.socialaccount',

    'allauth.socialaccount.providers.google',

Other providers that you can use to sign up your users are:

'allauth.socialaccount.providers.agave',
'allauth.socialaccount.providers.amazon',
'allauth.socialaccount.providers.apple',
'allauth.socialaccount.providers.auth0',
'allauth.socialaccount.providers.authentiq',
'allauth.socialaccount.providers.azure', 
'allauth.socialaccount.providers.baidu', 
'allauth.socialaccount.providers.bitbucket',
'allauth.socialaccount.providers.bitbucket_oauth2', 
'allauth.socialaccount.providers.digitalocean',
'allauth.socialaccount.providers.discord',
'allauth.socialaccount.providers.disqus',
'allauth.socialaccount.providers.dropbox', 
'allauth.socialaccount.providers.evernote',
'allauth.socialaccount.providers.exist',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.feedly',
'allauth.socialaccount.providers.figma',  
'allauth.socialaccount.providers.github',
'allauth.socialaccount.providers.gitlab',
'allauth.socialaccount.providers.globus',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.gumroad',  
'allauth.socialaccount.providers.instagram', 
'allauth.socialaccount.providers.linkedin',
'allauth.socialaccount.providers.linkedin_oauth2',
'allauth.socialaccount.providers.mailchimp',
'allauth.socialaccount.providers.meetup',
'allauth.socialaccount.providers.microsoft',  
'allauth.socialaccount.providers.patreon',
'allauth.socialaccount.providers.paypal',
'allauth.socialaccount.providers.persona',
'allauth.socialaccount.providers.pinterest', 
'allauth.socialaccount.providers.shopify',
'allauth.socialaccount.providers.slack',
'allauth.socialaccount.providers.snapchat',
'allauth.socialaccount.providers.soundcloud',
'allauth.socialaccount.providers.spotify',
'allauth.socialaccount.providers.stackexchange',
'allauth.socialaccount.providers.steam',
'allauth.socialaccount.providers.stripe',
'allauth.socialaccount.providers.telegram',
'allauth.socialaccount.providers.trainingpeaks',
'allauth.socialaccount.providers.trello',
'allauth.socialaccount.providers.yahoo',
'allauth.socialaccount.providers.yandex',  
'allauth.socialaccount.providers.zoho',
'allauth.socialaccount.providers.zoom',

Check out the documentation for a complete list of providers; Link here

Take note that you should create an account with the provider you have chosen for your web application. After creating an account, you will be provided with configuration files such as keys that you will use to connect. Here is an example of a configuration file you can use to authenticate with Google:

# Provider specific settings
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'APP': {
            'client_id': 'id_provided',
            'secret': 'secret_provided',
            'key': 'key_provided'
        }
    }
}

Finally, you need to add allauth URLs to your main accounts management app. to do that, add the following line to your main urls.py file:

urlpatterns = [

    path('accounts/', include('allauth.urls')),

]

That’s it for my seven essential libraries and packages you should never miss for your Django projects. At least you should not miss one of them. See you in my next article.

Share your love
Badi
Badi

Badi here, creator of ngangasn.com— A website dedicated to providing helpful information and how-to's of web development and hosting. Inspired by a fascination to write the most efficient code to make a computer laugh, & humans, Steve has a passion for organizing characters to create code and informative content.
What makes me happy?
Well, nothing like the feeling of finally figuring out that one pesky bug that's been driving me crazy.

Leave a Reply

Your email address will not be published. Required fields are marked *