EDITED: Updated on 05-June-2018 to add more tricks.
Django is a free and open source Python web application framework or collection of modules that makes development easier. It is well-known for its great documentation.
As good as the documentation is (and it is pretty impressive), it can still be confusing and difficult to navigate if you are are a beginner. There are some very good tutorials out there that give you the basics on how to get started using Django. (I highly recommend Python and Django Full Stack Web Developer Bootcamp by Jose Portilla on Udemy.) However, as informative as those tutorials are, they can't cover everything. In this article, I want to share some of the coolest tricks in Django that will make life easier as you learn.
Tip: Generating a random secret key
When you first create your project, Django creates a 'secret key' that is used to provide cryptographic signing to run the
application. What you may not know is that you can actually generate a secret key externally or independently from the
Django project. There are several reasons why you may wish to do this. Perhaps your original secret key was compromised
or maybe it contained characters that are not compatible with another application that you are using. In any case,
here is the code that you can run from the command line to have Python generate a new secret key that you can copy and
paste into your settings file. (You must have both Python and Django installed to run this code.)
$ python -c "from django.utils import crypto; print(':'.join(crypto.get_random_string(16) for _ in range(2)))"
Tip: Start the server using a different settings file
Another good resource for learning Django is Two Scoops of Django by Daniel and Audrey Roy Greenfield. This is a more advanced look into Django so make sure you have had some practice with the basics before diving into this one. Two Scoops does away with the default structure of Django projects and takes a more modular approach. Instead of having one settings.py file, you have a different settings file for each environment: base (applies to all), development, staging, and production. And each of these settings files contains only the settings that are relevant to that specific environment.
When you you have multiple settings files, you may have the need to run your application using different settings. A common scenario I have seen is when you are in a staging environment, but need to verify that the database is working before having all of the environmental variables set up yet. When you have a situation like this, Django lets you specify which settings file to use when running the application. Instead of using the normal python manage.py runserver command, the code looks like this:
$ python manage.py runserver --settings=config.settings.local
Tip: Importing and Exporting Data
One of the most useful tips I can share is how to import and export data from the database. I can not tell you how many times I have started a project and then scrapped it and started over from scratch. Repopulating a fresh database, whether it is from starting over or from finally moving into production can be painful unless you know how to do it via the command line.
First, some terminology. A
is a file which contains data that Django knows how to import into a database. It can be a JSON, XML or YAML file.
Django automatically looks for the
fixtures directory inside the app, but you can also specify a path in the command if you don't use a fixtures directory.
I typically create one as part of my project set up.
The two data managing commands are dumpdata for exporting data and loaddata for importing.
The dumpdata command has options that allow you to control what data is being dumped and where it is being dumped to. Note: If you do not specify a file name, Django will print this information to the screen. The example below dumps the data from the 'post' model in the 'blog' app into a JSON file named 'posts.json' using the local settings file.
$ python manage.py dumpdata blog.post --output=posts.json --settings=config.settings.local
command has options that allow you to choose which data to load and from what file. The example below loads the data from
the 'posts.json' file using the local settings file. The file itself specifies the apps and models.
$ python manage.py loaddata posts.json --settings=config.settings.local
The code below is an example of a JSON file that contains sites.
You can see how this would make life much easier than entering all of this information by hand.
Tip: Customizing the Admin
One of my favorite tips is how to customize the Django Admin. It's a fairly neat interface already, but you can make slight changes (or big ones) that can make your life much easier. You can change the way the Admin looks at the field level within different models or change the way the entire page looks by copying the admin/index.html page and modifying it.
One of the best "how to" articles is found within the Django documentation itself in the tutorial
Writing your first Django app, part 7. Another good article is
5 Ways to make Django Admin Safer by Haki Benita.
Some of the changes that I regularly make are:
- Change the name of the Admin site.
- Add the "Save" functions to the top of the model edit page (as well as the bottom).
- Group similar fields together on one line.
These can be changed in the admin.py file of the app.
from django.contrib import admin
# Customize Admin Site header
admin.sites.AdminSite.site_header = 'KruizeTech Administration'
admin.sites.AdminSite.site_title = 'KruizeTech Administration'
fieldsets = (
# Group the title and slug field on the same line
'fields': (('title', 'slug'), 'lead', 'body', ),
'fields': ('categories', 'tags', ),
# Add the save feature to the top of the form
save_on_top = True
Another Admin Tip: Limiting Filters
When you add
list_filter to your admin model, the Admin page allows you to filter the list by the fields you have given. However, if you use a field like 'User', the filter will display ALL users that exist in the database. Django gives you a way to limit this list to just the choices used in model using Django's build-in
For example, if my database has models for countries and states, I configure my StateAdmin model to filter the list of states by country, but only show the countries used in the state records as filter options. Here's how that would look:
class StateAdmin(admin.ModelAdmin): list_display = ['name', 'state_code', 'country'] list_filter = [('country', admin.RelatedOnlyFieldListFilter)]
This results in a shorter list of countries in the filter box and is much less clutter on your Admin dashboard.
Tip: Django flatpages app
Django comes with an app called flatpages . It's nice and easy to use for simple pages like 'About', 'Terms of Service', or 'Privacy Policies' that do not require a whole application. It is fairly simple to set up and easy to use. Just add the app to your INSTALLED_APPS setting and add the URL entry in your project URL file. (See the Django docs here for details.)
Tip: Django admindocs
One of the features that I use frequently in Django is the
, especially when I am using third-party packages where I am not as familiar with the back-end. To use this application,
you must add it to your
INSTALLED_APPS setting and add the URL path to your project URL file. (See the Django docs
here for more information.)
Once installed, this app pulls information in from the docstrings on your models, views, template tags, template filters, and templates as well as documenting all of the information from the built-in and third-party apps that you are using. This app can be a life-saver when trying to troubleshoot and gives you incentive to be thorough in your documentation efforts throughout your applications.
Hope you enjoyed these tips. Happy coding!