How to wrap text in Django admin(set column width)

Question:

enter image description hereI have a model Item

class Item(models.Model):
    id = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=140, blank=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True)

and my model admin

class ItemAdmin(admin.ModelAdmin):
   list_display = ['item_view', 'description', 'item_price', 'seller_view', 'added_on']
   actions = ['add_to_staff_picks']
   search_fields = ('description', 'title')

   def item_view(self, obj):
       item = obj
       url = reverse('admin:%s_%s_change' % ('adminuser', 'item'), args=(item.id,))
       if item.is_active:
          return '<font color="green">%s</font>' % (base64.b64decode(item.title))
       return '<font color="red">%s</font>' % (base64.b64decode(item.title))
       item_view.allow_tags = True
       item_view.short_description = 'Title'

and I need to show the field ‘title’ wrapped in my Django admin site(fix a width for title column) . How can I achieve that. please help.

Asked By: itsme

||

Answers:

If I understand you correctly you need the list_display property of the Django’s admin class.

Example “admin.py”

from django.contrib import admin

from path.to.your.app.models import Item

class ItemAdmin(admin.ModelAdmin):
    """
    Your ``Item`` model admin.
    """
    # List here all the fields that are to be displayed in the listing view.
    list_display = ('title', 'description',)

admin.site.register(Item, ItemAdmin)

Updated answer (2014-08-08)

Your admin module:

from django.conf import settings

class ItemAdmin(admin.ModelAdmin):
    # Some other code
    class Media:
        js = (
            '{0}js/jquery-1.10.2.min.js'.format(settings.STATIC_URL),
            '{0}js/jquery.expander.min.js'.format(settings.STATIC_URL),
            '{0}your_app/js/your_code.js'.format(settings.STATIC_URL),
            )

Let’s say, we’re going to use the jquery.expander plugin https://github.com/kswedberg/jquery-expander

Then your “your_code.js” would look as follows:

;
$(document).ready(function() {
   // Assuming that your element that would be wrapped comes as second td (column).
   // If not, adjst the nth-child(2). 
   $('#result_list tbody tr td:nth-child(2)').each(function(e) {
        $(this).expander({
            slicePoint:       50,  // default is 100
            expandSpeed: 0,
            expandEffect: 'show',
            collapseSpeed: 0,
            collapseEffect: 'hide',
            expandPrefix:     ' ', // default is '... '
            expandText:       '[...]', // default is 'read more'
            userCollapseText: '[^]'  // default is 'read less'
        });
   });
});
Answered By: Artur Barseghyan

add a function to your Model, then in modelAdmin call the function

#Model
def shortTitle(self):
    return str(self.title)[:50]

#modelAdmin
class ItemAdmin(admin.ModelAdmin):
   list_display = ['shortTitle', ...
Answered By: Alex

ALTERNATIVE ANSWER

list_display = ('title_name', 'description',)


 def title_name(self, obj):
    if obj.tracking_no:
        line_length = 20 
        lines = [obj.title[i:i+line_length] + 'n' for i in range(0, len(obj.title), line_length)]  
        return ''.join(lines)
    return obj.title_name

track.short_description = "title"
Answered By: Lenate John

This is the answer using html. You add this as a method in your ModelAdmin class:

    def title_(self, obj):
        from django.utils.html import format_html
        return format_html(
            f'<div style="width: 100px; word-wrap: break-word">{obj.title}</div>'
        )

Then you add title_ to your list_display declaration instead of title.

Answered By: pandichef