django-bleach

3.1.0 · active · verified Fri Apr 17

django-bleach is a Django package that provides easy integration of the bleach HTML sanitization library with Django models and templates. It offers model fields and template filters to clean user-supplied HTML, preventing XSS vulnerabilities. The current version is 3.1.0, with a release cadence that generally follows Django and `bleach` updates, releasing new major versions for significant dependency bumps or framework compatibility changes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a `BleachHTMLField` in a Django model. This field will automatically sanitize any HTML input based on the `tags` and `attributes` provided, or global settings configured in `settings.py`. It's crucial to explicitly define what HTML elements and attributes are permitted to prevent Cross-Site Scripting (XSS) vulnerabilities. You can define global settings like `BLEACH_ALLOWED_TAGS`, `BLEACH_ALLOWED_ATTRIBUTES` in your `settings.py` file.

import os
from django.db import models
from django_bleach.models import BleachHTMLField

# Configure settings (e.g., in settings.py or test setup)
# You can also pass these directly to the field constructor
# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings')
# os.environ['BLEACH_ALLOWED_TAGS'] = "['p', 'a', 'strong', 'em']"
# os.environ['BLEACH_ALLOWED_ATTRIBUTES'] = "{'a': ['href', 'title']}"

class Article(models.Model):
    title = models.CharField(max_length=200)
    # Use BleachHTMLField for content that might contain HTML
    content = BleachHTMLField(
        blank=True,
        null=True,
        # Field-specific allowed tags and attributes override global settings
        tags=['p', 'a', 'h1', 'h2', 'strong', 'em', 'img'],
        attributes={'a': ['href', 'title'], 'img': ['alt', 'src']},
        strip_tags=False, # Do not strip tags not explicitly allowed (default is False)
        strip_comments=True # Strip HTML comments (default is True)
    )

    def __str__(self):
        return self.title

# Example usage (after creating and migrating the model):
# article = Article.objects.create(title='My Article', content='<h1>Hello</h1><p>This is <strong>safe</strong> content.</p><script>alert("XSS!")</script>')
# print(article.content) # Script tag should be removed.

view raw JSON →