django admin table columns wrap text into multiple lines django

# Step 1: Create a custom CSS file (e.g., custom_admin.css) in your Django app's static directory
# File Path: your_app/static/admin/css/custom_admin.css

.admin-table th, .admin-table td {
    white-space: normal;
}
# Step 2: Create a Django Admin class for the model you want to modify
# File Path: your_app/admin.py

from django.contrib import admin
from your_app.models import YourModel

class YourModelAdmin(admin.ModelAdmin):
    class Media:
        css = {
            'all': ('admin/css/custom_admin.css',),  # Path to your custom CSS file
        }

# Register your model with the custom admin class
admin.site.register(YourModel, YourModelAdmin)
# Step 3: Apply the changes to the Django admin interface
# Run the following command in your terminal
python manage.py collectstatic

Explanation for each step:

  1. Create a custom CSS file: This step involves creating a CSS file (custom_admin.css) within your Django app's static directory. In this file, a CSS rule is defined to modify the appearance of table header cells (th) and table data cells (td). The white-space: normal; property allows text within these cells to wrap into multiple lines if needed.

  2. Create a Django Admin class: In the admin.py file of your Django app, create a custom admin class (YourModelAdmin) for the model (YourModel) you want to modify. Inside this class, define a nested Media class that specifies the path to the custom CSS file created earlier using the css attribute.

  3. Apply the changes to the Django admin interface: After making these changes, run python manage.py collectstatic in your terminal. This command collects static files from all your apps into a single location, including your custom CSS file, ensuring it's available to the Django admin interface.

These steps modify the CSS styling of the Django admin table for a specific model, allowing text within table columns to wrap into multiple lines for better readability.