1

so I've defined readonly_fields in Django ModelAdmin with a callable which looks like this:

class TestAdmin(admin.ModelAdmin):
    readonly_fields = ("test_field_with_whitespace",)

    def test_field_with_whitespace(self, obj):
        return '     Hello      World'

In the corresponding admin view the readonly field is shown as "Hello World" - so without the whitespaces.

What can I do to show the whitespaces?

RaideR
  • 869
  • 1
  • 12
  • 33

2 Answers2

2

This is nothing to do with the modeladmin. HTML itself strips all whitespace. If you need it to show precisely then you will need to wrap it in a <pre> tag - and since you are now sending HTML you need to mark it as safe to avoid autoescaping.

from django.utils.safestring import mark_safe
...
return mark_safe('<pre>     Hello      World</pre>')
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thanks for your answer. I was confused because a normal models.Textfield will be shown with all whitespaces in the admin view - a readonly field not.
     is not exactly what I'm looking for because it comes with a specific styling. But I can figure out where to go from here - e.g. replace all whitespaces with   and so on
    – RaideR Dec 12 '18 at 08:57
  • If you are rendering user input do **NOT** use mark_safe as you will be exposed to js injection attacks. – Jonatan Apr 12 '22 at 13:46
0

The accepted answer is vulnerable to js injection attacks.

To not be vulnerable to js injection attacks it's better to add custom css to the admin model. One way to achieve this is with:

@admin.register(MyModel)
class SomeAdmin(admin.ModelAdmin):

    class Media:
        css = {
            'all': ('css/admin.css',),
        }

admin.css file:

div.readonly {
    white-space: pre;
}
Jonatan
  • 1,182
  • 8
  • 20