Skip to content Skip to sidebar Skip to footer

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 . What's the easiest way to do this? I know about all

Solution 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

classPost(models.Model):
    title = models.CharField()
    content = BleachField()

2. In your forms:

classPostForm(forms.ModelForm):
    content = BleachField()
    classMeta:
        model = Postfields= ['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

Solution 2:

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_htmlmark_safe(): https://docs.djangoproject.com/en/1.9/ref/utils/#django.utils.safestring.mark_safe

Post a Comment for "Django Admin: Allowing Some Html In User Input"