Django shortcuts

/ #Django


Django has some shortcuts to help you speed up your development process even more. In this post we'll cover a few of them.

How to use the shortcuts

All of Django's lives inside the django.shortcuts module and you can import them like this:

from django.shortcuts import render, redirect, get_object_or_404, get_list_or_404

render

Params: render(request, template_name, context=None, content_type=None, status=None, using=None)

An example of the render function

from django.shortcuts import render

def home(request):
    context = {'title': 'Home'}
    return render(request, 'home.html', context)

If it wasn't for this shortcut it would look like this

from django.http import HttpResponse
from django.template import loader

def home(request):
    template = loader.get_template('home.html')
    context = {'title': 'Home'}
    return HttpResponse(template.render(context, request))

As you can see render requires a less code and is more readable. Using the render function makes the code look more neat and is easier to maintain.

redirect

Params: redirect(to, permanent=False, *args, **kwargs)

An example of the redirect function

from django.shortcuts import redirect

def home_view_redirect(request):
    """ Redirect to a view (view-name) """
    return redirect('view-name', slug='this-is-an-example')
    
def home_hardcode_redirect(request):
    """ Redirect to a hardcoded url ('/about/') """
    return redirect('/about/')

This code will do the same as this (the view redirect is not possible)

from django.http import HttpReturnRedirect

def home_hardcode_redirect(request):
    """ Redirect to a hardcoded url ('/about/') """
    return HttpReturnRedirect('/about/')

The amount of code and readability is about the same, but the redirect shortcut makes it possible to redirect directly to another view. It also looks slightly better.

get_object_or_404

Params: get_object_or_404(klass, *args, **kwargs)

An example of how to use this shortcut

from django.shortcuts import get_object_or_404

from .models import Post

def detail(request, slug):
    post = get_object_or_404(Post, slug=slug)

This code will do the same this as this

from django.http import Http404

from .models import Post

def detail(request, slug):
    try:
        post = Post.objects.get(slug=slug)
    except Post.DoesNotExist:
        raise Http404("No post matches the given slug")

The get_object_or_404 saves you a little bit of code and it looks much better. Here is another example if you want to use a queryset instead of the model

from django.shortcuts import get_object_or_404

from .models import Post

def detail(request, slug):
    queryset = Post.objects.filter(published=True)
    post = get_object_or_404(queryset, slug=slug)

# Slightly better

def detail(request, slug):
    post = get_object_or_404(Post, published=True, slug=slug)

get_list_or_404

Params: get_list_or_404(klass, *args, **kwargs)

An example of how to use the get_list_or_404 shortcut

from django.shortcuts import get_list_or_404

from .models import Post

def home(request):
    posts = get_list_or_404(Post, published=True)

Here is the same code, but without the shortcut

from django.http import Http404

from .models import Post

def home(request):
    posts = list(Post.objects.filter(published=True))
    if not posts:
        raise Http404("No posts matches the given query.")

Summary

The shortcuts can be quite helpful at times and makes your code more maintainable. But I have added the examples of how the code would look without the shortcuts because it's important to know how they work and how to work without them when you need to.

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.