Mdjon26
Mdjon26

Reputation: 2255

Getting HTML to linebreak in django admin's display

I have this as my django display

The code for doing this is:

class PurchaseOrder(models.Model):
    product = models.ManyToManyField('Product', null =True)

    def get_products(self):
        return "\n".join([p.products for p in self.product.all()])

class Product(models.Model):
    products = models.CharField(max_length=256, null =True)

    def __unicode__(self):
         return self.products

views.py:

class PurchaseOrderAdmin(admin.ModelAdmin):
   fields = ['product']
   list_display = ('get_products')

So I've attempted to do this:

from django.utils.html import format_html

 def get_products(self):
    return format_html(" <p> </p>").join([p.products for p in self.product.all()])

however, it's still not returning it in HTML. Or rather, the way I want it in the image

Upvotes: 3

Views: 2580

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

You need to set the field to allow tags for the HTML to show up in the admin list display:

class PurchaseOrder(models.Model):
    product = models.ManyToManyField('Product', null =True)

    def get_products(self):
        return "<br />".join([p.products for p in self.product.all()])
    get_products.allow_tags = True

See the docs for more information.

Upvotes: 2

Related Questions