Safe Filter for HTML

A snippet showing how to mark strings as safe HTML in templates.


# models.py

from django.db import models

class Snippet(models.Model):
    title = models.CharField(max_length=120)
    html = models.TextField()

    def __str__(self):
        return self.title
      

# admin.py

from django.contrib import admin
from .models import Snippet

@admin.register(Snippet)
class SnippetAdmin(admin.ModelAdmin):
    list_display = ("title",)
      

# templates/snippet_detail.html

<div>{{ snippet.html|safe }}</div>
      
Explanation:
  • By default Django escapes variables; |safe marks a value as safe HTML.
  • Only use on trusted content; sanitize user-generated HTML before storing.
  • Prefer server-side sanitization (e.g., Bleach) for untrusted input.
  • Category Templates
  • Total Views 1055
  • Last Modified 23 January, 2026
  • Tags #templates #safe #html #filter
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.