1. Code
  2. Python
  3. Django

10 Insanely Useful Django Tips

Scroll to top
Read Time: 8 min

There are quite a few great little tricks and tips you can use in your Django projects that will speed up development and save many headaches in the long run. From basic to obscure, these tips can help any skill-level of programmer become more adept with Django and all its glory.

Django is an excellent framework for Python. While it may not get as much ink as other popular frameworks like Rails, it is just as polished a framework as any of the rest. It puts plenty of emphasis on the DRY principle (Don't Repeat Yourself) in clean coding by automating many of the processes in programming.

1. Use Relative Paths in the Configuration

"Relative path" means using the path relative to the current working directory to define files rather than hard-coding the full path. For some reason, projects tend to be moved around from time to time. This can be an absolute bear to deal with if you don't first plan ahead for the possibility. If you don't use relative paths, the project will break if another person is working on the same project or the application is deployed to the server. Rob Hudson has an excellent technique to ensure that your Django deployments can be moved around with ease, only having to edit a few lines of code in your settings files.

My default Django settings file has changed over time to now include settings that do not depend on the location of the project on the file system. This is great in a team environment where more than one person is working on the same project, or when deploying your project to a web server that likely has different paths to the project root directory.

The correct way to define the static directories is by following the relative path. By default, Django provides the BASE_DIR and even gives you a hint about how to define your paths.

# Build paths inside the project like this: BASE_DIR / 'subdir'.

BASE_DIR = Path(__file__).resolve().parent.parent

Here is how you would define the STATIC_ROOT and MEDIA_ROOT directories.

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Photo by kaet44.

2. Use the {% url %} Tag

Instead of hard-coding individual links, try using the backwards-compatible {% url %} tag to achieve the same result. This will give you the absolute URL so that if, heaven forbid, your Django project moves, the links will still remain intact.

Essentially, {% url %} takes a view name and its parameters and does a reverse lookup to return the queried URL. If you make changes to your file, the links won't break.

While it's not the most advanced tip, it's an excellent technique to use in your Django projects.

Photo by Dave_Apple.

3. Use select_related and prefetch_related

Unnecessary queries will always have adverse effects on database performance. Databases use foreign keys and many-to-many relationships to manage relationships between tables. select_related allows developers to fetch related objects in a foreign key relationship, while prefetch_related allows developers to fetch related objects in many to many or reverse foreign key relationships. These two methods will allow you to reduce the number of queries made to the database.

For example, suppose you have the following models:

class Author(models.Model):
    full_name = models.CharField(max_length=100)
    def __str__(self):
        return self.full_name
class Course(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    author = models.ForeignKey(Author)
    def __str__(self):
        return self.title

Let's perform queries using select_related and prefetch_related.

>>> from mysite.models import Course,Author
>>> tutorials = Course.objects.select_related('author').all()
>>> tutorials
<QuerySet [<Course: Web development with Django>, <Course: understanding django>, <Course: python sysyems>]>
>>> tutorials1 = Course.objects.prefetch_related('author').all()
>>> tutorials1
<QuerySet [<Course: Web development with Django>, <Course: understanding django>, <Course: python sysyems>]>

4. Use a Separate Media Server

Django allows you to serve static files in your development environment but not your production environment. Why? It's not efficient. 

Serving static files on the same server as your Django application can slow things down. The best solution is to use a dedicated server such as nginx, a cloud service, or a CDN. Some of the storage cloud service solutions available are:

  • Cloudinary
  • Amazon S3
  • Google cloud storage
  • Azure file storage

These provide a faster way of serving static files, hence improving your website performance. By using a separate server to house and serve these static files, your performance won't suffer. If you don't want to buy a server, you could use Amazon S3 to house the files relatively cheaply.

Django deliberately doesn't serve media for you, and it's designed that way to save you from yourself. If you try to serve media from the same Apache instance that's serving Django, you're going to absolutely kill performance. Apache reuses processes between each request, so once a process caches all the code and libraries for Django, those stick around in memory. If you aren't using that process to service a Django request, all the memory overhead is wasted.

Photo by winkyintheUK.

5. Use the Debugger Toolbar

Debugging tools for any language are invaluable. They speed up development by spotting errors in your code and potential pitfalls. The Django debug toolbar helps with debugging code, and it could greatly help any developer.

The toolbar itself is a piece of middleware that instantiates each panel object on request, and performs processing and rendering as the response is being written back to the browser. In this way it is essentially a set of middleware classes (the panels) grouped together to display a single toolbar. Each panel subclasses a base panel class and overrides a few methods to render the toolbar.

The Django debug toolbar is also used to observe slow-running queries and can help with database optimization. Here is a screenshot showing the toolbar in action.

django debug toolbardjango debug toolbardjango debug toolbar

6. Use Django Unit Testing

Unit testing is a great way to ensure that any changes you make to the code work as expected and don't break any older code to maintain backwards compatibility. A great feature of Django is that it's incredibly easy to write unit tests. Django offers the ability to use doctest or unittest straight out of the box.

Django's documentation offers a great tutorial and some sample code on how to set up unit tests to keep your code running smoothly and spot any nasty bugs.

Photo by Dave_Apple.

7. Use a Virtual Environment to Manage Dependencies

Unlike other programming languages, Python is not good at managing application dependencies. Virtual environments allow you to separate system dependencies from application dependencies. For example, suppose you have Python 3.9 globally installed on your operating system. In that case, a virtual environment will allow you to use different versions of Python in different projects on the same machine. Another great tip is to use the requirements.txt file to list every library or package used in your project.

Different versions of particular packages might cause things to break. If you're interested, you can read more about virtual environments.

Photo by quimpg.

8. Use Class-Based Views

Django provides class-based views, which abstract the implementation of some repetitive tasks. Class-based views are reusable and make it easy to add logic with minimal code changes. For example, look at the code below for submitting a form using class-based and function views.

# function based view

def member_form(request):
    if request.method == 'POST':
        form = MemberForm(request.POST)
        if form.is_valid():
            member = Member( 
                first_name = request.POST['first_name'],
                last_name = request.POST['last_name'],
                email = request.POST['email'],
                address = request.POST['address'],
                mobile = request.POST['mobile'])
            return HttpResponse("Member Added")
        form = MemberForm()
    return render(request, 'mysite/member_form.html', {'form': form})
# Class Based View: 

from django.views.generic import CreateView
from .models import Member
class SubmitFormView(CreateView):
    model = Member 
    fields = ['first_name', 'last_name', 'email', 'address', 'mobile'] 
    template_name = 'mysite/member_form.html' 
    def form_valid(self, form): 
        return HttpResponse("Member Added")

As you can see above, the class-based view will need minimal changes if the logic changes.

Photo by Vince Huang.

9. Use Memcache

If performance is going to be an issue with your Django-powered application, you'll want to install some sort of caching. While Django offers many options for caching, the best by far is memcached. Other types of caching available in Django include:

  • database caching
  • file system caching
  • local caching
  • dummy caching
Photo by lastrandy.

10. Stop Hacking Scripts Together and Just Use Django

If you still don't fully understand Django's power, there's a logical reason for using Django in your next project: You save time hacking together designs with different sets of software. According to Jeff Croft, one of the co-creators of Django:

Now, if you're used to building sites using a blogging app (WordPress, TXP, etc.) as a CMS, you're used to getting all that for free. But you're also getting a lot of things built-in that maybe you don't want (unless, of course, you're building a blog). The limitation I ran across in using a blogging app for my personal site is that I wanted it to be more than just a blog. As soon as I tried to hack a blog into a photo gallery, or a links feed, or a statistics database, a game of Sudoku, or whatever else I could think of, things started to get crufty. I also built a website in which I tried to use a discussion forums app (vBulletin) as a CMS, and that had the same results. It worked—sort of—but it wasn't extensible, was very hackish, and just generally was inelegant.

With Django, you get all of these things and none of the limitations of a blogging app.

Django allows you to expand your website in literally any direction, without having to worry about hacking the design or making sure the scripts and databases are compatible. It just works.

Photo by JennyHuang.

This post was updated with contributions from Esther Vaati.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.