[Fixed]-Django admin: allowing some HTML in user input

1👍

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

0👍

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

👤Adam

Leave a comment