I try to display text with newlines in list display of admin side of Django.
class MyModelAdmin(admin.ModelAdmin):
list_display = ('example')
def example(self,obj):
return 'TYPE : %s \n RATE : %s \n FAMILY %s'
However, it is displayed without newlines like TYPE : xxx RATE : yyy FAMILY zzz
.
How can I do this in Django admin ?
In Django 2/3, you should use format_html
, since allow_tags
has been deprecated. So, the example code becomes:
from django.utils.html import format_html
class MyModelAdmin(admin.ModelAdmin):
list_display = ('example',)
def example(self, obj):
return format_html('TYPE : %s<br />RATE : %s<br />FAMILY %s' % (
self.type, self.rate, self.family))
You have to use br instead of a \n
, and specify that this field is allowed to use html tags:
def example(self):
return 'TYPE : %s<br>RATE : %s<br>FAMILY %s' % (self.type,
self.rate,
self.family)
example.allow_tags = True
Or you can use some more elegant HTML way of formatting your output (like wrapping each in a span element with a certain class, and add some css to make then render below each other).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With