Ali Soltani
Ali Soltani

Reputation: 619

How can I remove a specific HTML tag in Django templates?

I tried to use striptags in a Django template, but it removes all HTML tags. I just want to remove a specific HTML tag, for example <p> or <h1> tags. How can I do it in template?

This is my 'Post' model: POST MODEL

I have a field named text and my view is like this: DRAFT VIEW

I get and filter my Post objects/fields in get_queryset() method and return them to post_draft_list.html and then get text filed {{post.text}}. text contains some html tags and I want to remove them. now if I want to clean text field by bleach, how can I do that in my views (get_queryset)?

Upvotes: 3

Views: 2402

Answers (2)

Mohammad Jafar Mashhadi
Mohammad Jafar Mashhadi

Reputation: 4251

You may also use this snippet however the snippet uses regular expressions to parse HTML which is NOT a good idea. So I suggest going with bleach as Astik mentioned too.

Upvotes: 0

Astik Anand
Astik Anand

Reputation: 13047

Try:

import bleach

filtered_text = bleach.clean(data_text, tags=[u'a', u'i', u'li', u'ol', u'ul'])

Allow only those tags what you need, in tags.

For more information you can follow bleach, beacuse removetags filter was depreciated from django 1.8 onwards for security purpose.

Upvotes: 2

Related Questions