Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Admin: list_display TextField

I'm trying to display the first 10 characters of a TextField on a list_display.
Is it possible in the admin interface ?

like image 605
Pierre de LESPINAY Avatar asked Mar 29 '12 09:03

Pierre de LESPINAY


2 Answers

You can define a callable that returns the first 10 characters of the field, and add that to list_display.

More information see the Django docs for list_display.

like image 180
Alasdair Avatar answered Oct 06 '22 23:10

Alasdair


myapp/admin.py
from django.contrib import admin
from django.utils.text import Truncator
from django.db import models
from .models import Product

def truncated_name(obj):
    name = "%s" % obj.name
    return Truncator(name).chars(70)

class ProductAdmin(admin.ModelAdmin):

    list_display = ['id',  truncated_name, 'category', 'timestamp',]
    list_display_links = [truncated_name]
    list_filter = ['category']

    class Meta:
        model = Product

You can also override the fields like so:

    formfield_overrides = {
        models.CharField: {'widget': TextInput(attrs={'size': '20'})},
        models.TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 40, 'style': 'height: 1.5em;'})},
}
like image 28
jturi Avatar answered Oct 06 '22 21:10

jturi