Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rich text editor in Django admin - Hiding the HTML tags in the change list

I am developing a Django project where admins are able to style some content using TinyMCE. Everything works fine, except for an annoying detail.

For some model it happens that a field edited in rich text mode needs to be shown in the change list. What happens is that this field is then displayed with its HTML tags. What I would like to do is to have the equivalent of

{{ field|striptags }}

inside the change list.

Unfortunately things are not as simple as overriding an admin template, since the content already arrives at the template wrapped with the admin HTML (<td>). So if I simply replace

<tr class="{% cycle 'row1' 'row2' %}">{% for item in result %}{{ item }}{% endfor %}</tr>

with

<tr class="{% cycle 'row1' 'row2' %}">{% for item in result %}{{ item|striptags }}{% endfor %}</tr>

inside 'admin/templates/change_list_results.html' the results table appears unstyled.

How can I have a decent preview of these fields in the change list?

like image 631
Andrea Avatar asked Dec 27 '22 06:12

Andrea


2 Answers

You could create an extra property on your model that returns the stripped field and use this in list_display.

class YourClass(models.Model):
    ....

    @property
    def html_stripped(self):
       from django.utils.html import strip_tags
       return strip_tags(self.html_field)

and in your ModelAdmin:

list_display = ['html_stripped', ...]

The docs for list_display mention a few other options and give you more details on this topic.

like image 59
arie Avatar answered Dec 31 '22 12:12

arie


If the problem is that you don't want to see the tags, but want them to render, you may want to try this:

from django.utils.safestring import mark_safe
class SomeModel(models.Model):
    some_field = models.CharField(max_length=50)
    def some_field_html(self) :
        return mark_safe(self.some_field)

and then in the model admin use list_display.

list_display = ('some_field_html')

"A few special cases to note about list_display: ... If the string given is a method of the model, ModelAdmin or a callable, Django will HTML-escape the output by default. If you'd rather not escape the output of the method, use the mark_safe function on return."

like image 38
Francis Yaconiello Avatar answered Dec 31 '22 14:12

Francis Yaconiello