0

Would like to achieve this, example:

models.py

class Theory(models.Model):
    sort = models.PositiveIntegerField(default=1, blank=False, null=False)
    title = models.CharField(max_length=500)
    title_url = models.SlugField(max_length=500)
    graphics = models.ImageField(upload_to='theory', blank=True)
    description = RedactorField(blank=True)

    def __unicode__(self, ):
        return self.title

Inside the

description = RedactorField(blank=True)

will be always UL that has 3, 10, 8 or other amount of <li> tags. Maybe later will be added couple paragraphs, but for now there is only UL for each new Object (Theory)

Let's say my template variable holds description from wysiwyg editor in Django Admin

<ul>
    <li>Theory of Relativity</li>
    <li>Interstellar</li>
    <li>5D</li>
    <li>Black Hole</li>
    <li>Tesseract</li>
</ul>

index.html

{% for text in space %}
    {{ text.description | safe }}
{% endfor %}

This will output the HTML above.

My goal is to do this:

Theory of Relativity, Interstellar, 5D, Black Hole, Tesseract

I know I can do:

{% for text in space %}
    {{ text.description | safe | striptags }}
{% endfor %}

Output is going to be:

Theory of RelativityInterstellar5DBlack HoleTesseract

How can I achieve with Django and Python to Striptags + comma separated but precise phrases.

I know I can put commas in the Admin in the editor, but I cannot do that. I need HTML output that I am using as UL somewhere else on the page, but I need also that output.

4

1 回答 1

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')])
于 2015-09-17T19:38:50.757 回答