how to wrap text in django admin(set column width)

  • Last Update :
  • Techknowledgy :

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', ...

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)

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

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'
      });
   });
});

Suggestion : 2

You'll have to choose width and or height as limiting factors for your columns. Assuming you can't dictate the content length, you could choose truncating what is shown. ,as shown in Set the table column width constant regardless of the amount of text in its cells? and Using CSS to create table cells of a specific width with no word wrapping , it is hard or impossible to set the table column width directly without fiddling with the table layout and width settings; alternatively, you could wrap every content in a div, and then apply your formatting to those divs. ,The color changes depending on the truth of the falsity in the loop {% for%}. Django, Python, bootstrap,Alternatively, use "white-space: nowrap", and omit the height; then the cell is just truncated (but users can scroll).

To achieve this in tables2, I overrode the table.Column:

class DivWrappedColumn(tables.Column):

def __init__(self, classname=None, *args, **kwargs):
self.classname=classname
super(DivWrappedColumn, self).__init__(*args, **kwargs)

def render(self, value):
return mark_safe("<div class='" + self.classname + "'>" +value+"</div>")

create the column in the table:

    custom_column = DivWrappedColumn(classname = 'custom_column')

and then apply the css:

div.custom_column {
   white - space: normal;
   width: 200 px;
   height: 45 px;
}
# assume columns c1 and c2 that should be only as wide as needed
# to fit their content
# and a column c3 which takes up the rest of the table width

class MyTable(tables.Table):

   def __init__(self, * args, ** kwargs):
   self.columns['c1'].column.attrs = {
      "td": {
         "style": "width:1%;"
      }
   }
self.columns['c2'].column.attrs = {
   "td": {
      "style": "width:1%;"
   }
}

Suggestion : 3

The field names in list_display will also appear as CSS classes in the HTML output, in the form of column-<field_name> on each <th> element. This can be used to set column widths in a CSS file for example.,The field names in list_display will also appear as CSS classes in the HTML output, in the form of column-<field_name> on each <th> element. This can be used to set column widths in a CSS file for example. ,As with the fields option, to display multiple fields on the same line, wrap those fields in their own tuple. In this example, the first_name and last_name fields will display on the same line:,To display multiple fields on the same line, wrap those fields in their own tuple. In this example, the url and title fields will display on the same line and the content field will be displayed below them on its own line:

from django.contrib
import admin
from myapp.models
import Author

class AuthorAdmin(admin.ModelAdmin):
   pass
admin.site.register(Author, AuthorAdmin)
from django.contrib
import admin
from myapp.models
import Author

admin.site.register(Author)
from django.contrib
import admin
from.models
import Author

@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
   pass
from django.contrib
import admin
from.models
import Author, Editor, Reader
from myproject.admin_site
import custom_admin_site

@admin.register(Author, Reader, Editor, site = custom_admin_site)
class PersonAdmin(admin.ModelAdmin):
   pass
from django.contrib
import admin

class AuthorAdmin(admin.ModelAdmin):
   date_hierarchy = 'pub_date'
date_hierarchy = 'pub_date'

Suggestion : 4

Last modified: Apr 28, 2022, by MDN contributors

urlpatterns += [
   path('catalog/', include('catalog.urls')),
]
urlpatterns = [
   path('', views.index, name = 'index'),
]
<a href="{% url 'index' %}">Home</a>.
from django.shortcuts
import render

# Create your views here.
from.models
import Book, Author, BookInstance, Genre

def index(request):
   ""
"View function for home page of site."
""

# Generate counts of some of the main objects
num_books = Book.objects.all().count()
num_instances = BookInstance.objects.all().count()

# Available books(status = 'a')
num_instances_available = BookInstance.objects.filter(status__exact = 'a').count()

# The 'all()'
is implied by
default.
num_authors = Author.objects.count()

context = {
   'num_books': num_books,
   'num_instances': num_instances,
   'num_instances_available': num_instances_available,
   'num_authors': num_authors,
}

# Render the HTML template index.html with the data in the context variable
return render(request, 'index.html', context = context)
<!DOCTYPE html>
<html lang="en">
<head>
  {% block title %}<title>Local Library</title>{% endblock %}
</head>
<body>
  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
</body>
</html>