Using safe filter in Django for rich text fields

后端 未结 4 1229
半阙折子戏
半阙折子戏 2021-01-11 14:33

I am using TinyMCE editor for textarea fileds in Django forms.

Now, in order to display the rich text back to the user, I am forced to use the \"safe\" filter in Dja

4条回答
  •  天命终不由人
    2021-01-11 15:14

    Use django-bleach. This provides you with a bleach template filter that allows you to filter out just the tags you want:

    {% load bleach_tags %}
    {{ mymodel.my_html_field|bleach }}
    

    The trick is to configure the editor to produce the same tags as you're willing to 'let through' in your bleach settings.

    Here's an example of my bleach settings:

    # Which HTML tags are allowed
    BLEACH_ALLOWED_TAGS = ['p', 'h3', 'h4', 'em', 'strong', 'a', 'ul', 'ol', 'li', 'blockquote']
    # Which HTML attributes are allowed
    BLEACH_ALLOWED_ATTRIBUTES = ['href', 'title', 'name']
    BLEACH_STRIP_TAGS = True
    

    Then you can configure TinyMCE (or whatever WYSIWYG editor you're using) only to have the buttons that create the allowed tags.

提交回复
热议问题