[Fixed]-Django striptags, comma separated keywords

1👍

My recommendation would be to not store this as HTML in your database, but rather the individual values, which you can then output as HTML or comma-separated list wherever you need.

You could do this formatting very easily on the server side and output it as properties of your model. Example:

# models.py

from django.template.defaultfilters import join as join_filter
from django.template.loader import render_to_string

class Theory(models.Model):

    title = models.CharField(max_length=300)

    @propery
    def as_html(self):
        return render_to_string('theories.html', {'theories': self.objects.all()})

    @property
    def as_comma_separated_list(self):
        return join_filter(self.objects.values_list('title', flat=True), ', ')

# theories.html

<ul>
    {% for theory in theories %}
    <li>{{ theory }}</li>
    {% endfor %}
</ul>

Now your templating is “dumb”, and you don’t have to do any expensive parsing of HTML after the fact with BeautifulSoup, etc.

If you do have to go the BeautifulSoup route, it’s not so tough:

from bs4 import BeautifulSoup

soup = BeautifulSoup(content, 'html.parser')
theories = ', '.join([li.text for li in soup.findAll('li')])

Leave a comment