Pieter
Pieter

Reputation: 923

Django admin: allowing some HTML in user input

By default, the Django admin strips away all HTML tags from user input. I'd like to allow a small subset of tags, say <a>. What's the easiest way to do this? I know about allow_tags, but it's deprecated. I also want to be careful about manually marking strings as safe that aren't.

Upvotes: 0

Views: 1178

Answers (2)

sakhala
sakhala

Reputation: 51

If external library isn't a burden for you, then you must try django-bleach, it will suffice your requirement. It returns valid HTML that only contains your specified allowed tags.

Configuration: in settings.py

BLEACH_ALLOWED_TAGS = ['p', 'b', 'i', 'u', 'em', 'strong', 'a']
BLEACH_ALLOWED_ATTRIBUTES = ['href', 'title', 'style']
BLEACH_STRIP_TAGS = True

Use cases: 1. In your models:

from django import models
from django_bleach.models import BleachField

class Post(models.Model):
    title = models.CharField()
    content = BleachField()

2. In your forms:

class PostForm(forms.ModelForm):
    content = BleachField()
    class Meta:
        model = Post
        fields = ['title', 'content']
  1. In your templates:

    {% load bleach_tags %}

    {{ unsafe_html|bleach }}

for more usage, I suggest you must read the documentation. Its quite easy and straight forward.

documentation

Upvotes: 1

Adam
Adam

Reputation: 550

You can use format_html() or mark_safe() in place of allow_tags. Although, like you were saying, mark_safe() probably isn't a good idea for user input.

format_html(): https://docs.djangoproject.com/en/1.9/ref/utils/#django.utils.html.format_html
mark_safe(): https://docs.djangoproject.com/en/1.9/ref/utils/#django.utils.safestring.mark_safe

Upvotes: 0

Related Questions