Django Extensions – Installing and Implementing Extensions

Django Extensions

In this article, we will see the Django extensions functionality to extend the functionality offered by default in Django.

Various Important Django Extensions

The various important extensions provided are as follows:

  • Admin extensions
  • Command extensions
  • Debugger tags
  • Field Extensions
  • Model Extensions
  • Validators
  • Powershell

The detailed analysis is given in the following table

1. Admin Extensions

Some of the important Extensions are:

ExtensionDescription
ForeignKeyAutocompleteAdminEnables the admin app to show ForeignKey fields with a search input field.
ForeignKeyAutocompleteStackedInline
and ForeignKeyAutocompleteTabularInline
Similar to AutocompleteAd, these two classes enable search input field for Foreignkey fields in the AdminInline Classes
Admin Extensions

2. Command Extensions

Some of the most used command extensions are:

ExtensionDescription
Shell_plusEnhanced version of Django shell; has all the models autoloaded, hence we can work with ORM right away.
Create_template_tagGenerates the Template Tag directory structure within the specified application
generate_passwordIt generates a new password that can be used as a user password.
export_emailsExports email addresses in one of the following formats – Google, Outlook, LinkedIn, and VCard
graph_modelsIt creates a GraphViz dot file for apps. It combines the models of apps (passed) into a single model. The output is usually directed to a dot file.
run_scriptRuns a script in Django
sql_createGenerates the SQL to create a database, as specified in settings.py.
Command Extensions

We will see more about the shell – shell_plus in the later sections.

3. Debugger Tags

With Debugger Tags, we can debug Django templates easily. These template tags provide three filters – IPDB, PDB or WDB

The syntax is:

{% load debugger_tags %}

{% for object in objects %}
{{object | ipdb/pdb/wdb }}
{% endfor %}
FilterDescription
IPDBIt is an Ipython debugger tool used with Ipython to debug the model object (with which it is used)
PDBIt is the Normal Python Debugger to debug the model Object
WDBIt is a Web Debugger tool used to debug the python-based applications via the browser itself.
Debugger Tags

Note: To use the filters, we need to load the debugger tags at the top of the template files

{% load debugger_tags %}

4. Field Extensions

Some of the useful field extensions are:

RandomCharFieldCreates a unique random character with the specified length
DateTimeFieldDateTimeField automatically set its date when the object is first saved to the database
JSONFieldThis Text Field neatly serializes/deserializes JSON objects
Field Extensions

5. Model Extensions

These are the important Model extensions:

ExtensionDescription
ActivatorModelThis Abstract Base Class provides a status, activate_date and deactivate_date
TitleDescriptionModelThis Abstract Base Class model provides title field, which is a non-nullable CharField with maximum length –255, and a nullable description field.
Modle Extensions

6. Validators

Some of the important Validators provided by Django Extensions are:

ExtensionDescription
NoControlCharacterValidatorThis attribute ensures that the Control Characters like new lines or tabs are not allowed.
NoWhitespaceValidatorThis attribute ensures that the leading and trailing whitespace is not allowed.
HexValidatorEnsures that the string a valid hex string. Can Optionally also specify length, min_length and max_length parameters
Validators

Installing Django Extensions

We can install the extensions using pip command itself. Run the code

pip install django-extensions

We need to mention the Django extensions in our settings.py as well. So just add the following in the INSTALLED_APPS directory.

INSTALLED_APPS = [
    #......
    #......
    #......
    'django_extensions'
]

That’s it, the Django extensions are ready to use.

Implementing Django Extensions

Now we will see how to use important extensions in our Django project

1. Implementing Admin Extensions

Consider the BlogModel we built in a previous article with the following fields in the models.py file

from django.db import models

class BlogModel(models.Model):
    id = models.IntegerField(primary_key=True)
    blog_title = models.CharField(max_length=20)
    blog = models.TextField()

    def __str__(self):
        return f"Blog: {self.blog_title}"

Also, consider a CommentModel which contains the comments for a specific blog from the BlogModel Table. Add the Comment Model below the BlogModel in the models.py file:

class CommentModel(models.Model):
    your_name = models.CharField(max_length=20)
    comment_text = models.TextField()
    blog = models.ForeignKey('BlogModel', on_delete=models.CASCADE)
    
    def __str__(self):
        return f"Comment by Name: {self.your_name}"

Note that the blog field is the FK connecting the BlogModel. Now in the admin.py file, we will apply admin extensions to the Comment Model template.

from .models import *
from django_extensions.admin import ForeignKeyAutocompleteAdmin
 
@admin.register(CommentModel)
class BookModelAdmin(ForeignKeyAutocompleteAdmin):

    related_search_fields = {
        'blog':('blog_title',)
    }

    #Fields
    fields =('your_name','comment_text','blog')

Do check out the Admin Template article for more information about Admin templates

Now run the server and go to the admin site

Admin Extensions
Admin Extensions

See how the search option appears for the FK blog field.

2. Implementing shell_plus with Ipython

To run shell_plus with Ipython, we first need to install it.

Ipython is an interactive shell built for Python. It makes the shell environment efficient and easy to use. It provides useful environment tools and commands which we can use.

To install IPython, run the command:

pip install ipython

Now run the shell_plus along with ipython using the command below

python manage.py shell_plus --ipython
Shell Plus With Ipython
Shell Plus With Ipython

See, all the models present in the project are auto-loaded in the shell.

Some other important extensions

We will now see some of the most used extensions here

1. RandomCharField Extension

You can add this Field in your Model using the command below:

from django.db import models
from django_extensions.db.fields import RandomCharField

class ModelName(models.Model):
    Field1 = RandomCharField(length=12, unique =True, include_punctuation=True)

2. Validators

The syntax for this extension in models.py is:

from django_extensions.validators import HexValidator

class ModelName(models.Model):
    Field1 = models.CharField(max_length=80, validators=[HexValidator(length=64)])

Conclusion

That’s it, guys!! This was all about Django Extensions. I hope you have gained good knowledge about these extensions. Do check out the official Documentation for other Django Extensions.

We have come to an end of our Django tutorial series. Do check out our other articles on Django. Keep Coding !!