Skip to content

[DJ03] Avoid passing locals() as context to a render function

Rocio Aramberri edited this page Jun 13, 2021 · 3 revisions

The locals() function it's a built-in function that returns a dictionary containing all the symbols available at the current scope. It is sometimes used to save lines of code when using the render function.

Even though it could save you from writing a few lines of code, it's considered a dangerous practice, since it could potentially expose variables that you don't want to expose. Explicitly defining each of the values in the context is less dangerous and much better in terms of readability.

Don't

from django.shortcuts import render

def index(request):
    posts = Post.objects.all()
    return render(request, 'blog/index.html', locals())

Do

from django.shortcuts import render

def index(request):
    posts = Post.objects.all()
    context = {'posts': posts}
    return render(request, 'blog/index.html', context)