Escaping Variables in Templates

A snippet showing how to escape variables safely in templates.


# models.py

from django.db import models

class Comment(models.Model):
    author = models.CharField(max_length=80)
    text = models.TextField()

    def __str__(self):
        return f"{self.author}: {self.text[:20]}"
      

# admin.py

from django.contrib import admin
from .models import Comment

@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    list_display = ("author",)
      

# templates/comment_detail.html

<p>{{ comment.text }}</p>

<p>{{ comment.text|escape }}</p>

<{% autoescape off %}>{{ raw_html }}</{% autoescape off %}>
      
Explanation:
  • Django auto-escapes variables; use |escape for clarity.
  • Wrap fragments with {% autoescape off %} only for trusted content.
  • Never disable escaping for untrusted user input.
  • Category Templates
  • Total Views 1233
  • Last Modified 21 January, 2026
  • Tags #templates #escape #security #variables
Previous snippet
Safe Filter for HTML
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.