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']
-
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.
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
- Correct static files setting
- Django download generated file
- How to pass a django variable from html page to javascript