2020-11-30 06:48

Bleach cleaning allowed tags

I've set, in settings.py:

bleach.sanitizer.ALLOWED_TAGS = ['p','br','b','u','ul','li','font']
bleach.sanitizer.ALLOWED_ATTRIBUTES = {'font':['size']}

When I use it to clean up form input, as below, it uses the default list (in particular, removing <font> and <br>) of allowed tags, even though the last line correctly outputs the list above. Yes, I know that there's a bleach input field; I'm trying not to change my models.

if form.is_valid():
                this_standard.Description = bleach.clean(this_standard.Description)
                print bleach.sanitizer.ALLOWED_TAGS

If I manually pass the variables, it works:

this_standard.Description = bleach.clean(this_standard.Description,tags=bleach.sanitizer.ALLOWED_TAGS, attributes=bleach.sanitizer.ALLOWED_ATTRIBUTES)


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • weixin_39966163 weixin_39966163 5月前

    Hi , which python, bleach, and django versions are you using?

    点赞 评论 复制链接分享
  • weixin_39744316 weixin_39744316 5月前

    Hi :)

    Python 2.7, Django 1.9, Bleach 3.1.0

    It's working brilliantly otherwise - love it!

    点赞 评论 复制链接分享
  • weixin_39966163 weixin_39966163 5月前


    OK so, ALLOWED_TAGS is a constant and as you noticed modifying it and other constants won't change bleach's behavior since it creates a new variable in memory that bleach has no way of knowing about i.e.


    import bleach.sanitizer
    print(id(bleach.sanitizer.ALLOWED_TAGS))  # id prints the memory address for CPython
    bleach.sanitizer.ALLOWED_TAGS = ['p','br','b','u','ul','li','font']
    python2.7 ~/settings.py

    ^ the above addresses will vary per run, but the point is they aren't equal.

    It is a good idea to keep your ALLOWED_TAGS in one place like settings.py to have one place to update. I'd recommend reimporting that setting (from django.conf import settings then settings.BLEACH_ALLOWED_TAGS or something) and passing it to bleach.clean in your views/template helpers.

    Hope that makes sense

    点赞 评论 复制链接分享
  • weixin_39744316 weixin_39744316 5月前

    Ah, got it. So there's no way to modify the default tags and attributes, and I'll always need to explicitly pass some variable to the function?

    点赞 评论 复制链接分享
  • weixin_39966163 weixin_39966163 5月前

    Yeah, I don't have a clean way to set it via the pkg globals.

    点赞 评论 复制链接分享
  • weixin_39744316 weixin_39744316 5月前

    Cool, it still works, so that works for me - thanks again!

    点赞 评论 复制链接分享