Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin list_display newline

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 ?

like image 346
brsbilgic Avatar asked Oct 14 '11 19:10

brsbilgic


2 Answers

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))
like image 94
Cloud Artisans Avatar answered Nov 02 '22 09:11

Cloud Artisans


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).

like image 33
Ofri Raviv Avatar answered Nov 02 '22 08:11

Ofri Raviv