使django管理员在列表结果中显示不超过100个字符 [英] Make django admin to display no more than 100 characters in list results

查看:478
本文介绍了使django管理员在列表结果中显示不超过100个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的网站使用Django管理员,我想对我的一个模型的字段进行自定义。



我的一个模型有一个[TextField]可以是300个字符



当模型列在Django管理员中时,我想将文本显示的长度限制为100个字符。



如何实现?



admin.py:



pre> class ApplicationAdmin(admin.ModelAdmin):
model = Application
list_display = [title1,title2]

models.py:

  class Application(models.Model):
title1 = models.TextField(max_length = 300)
title2 = models.TextField(max_length = 300)
pre>

解决方案

您可以显示一个在ModelAdmin类中返回字段值截断版本的属性。利用内置的模板过滤功能,可以轻松实现。

  from django.template.defaultfilters import truncatechars#或truncatewords 

class Foo(models.Model):
description = models.TextField()

@property
def short_description(self):
return truncatechars self.description,100)

class FooAdmin(admin.ModelAdmin):
list_display = ['short_description']


I am using Django admin for my site and I would like to make a customization on how a field is displayed for one of my models.

One of my models has a [TextField] that can be 300 characters

When the model is listed in the Django admin, I would like to limit the length of the text displayed to 100 characters.

How can I accomplish this?

admin.py:

class ApplicationAdmin(admin.ModelAdmin):
    model = Application
    list_display = [ "title1", "title2"]

models.py:

class Application(models.Model):
    title1 = models.TextField(max_length=300)
    title2 = models.TextField(max_length=300)

解决方案

You can display a property that returns a truncated version of your field's value in your ModelAdmin class. Leveraging the built-in template filters makes this easy.

from django.template.defaultfilters import truncatechars  # or truncatewords

class Foo(models.Model):
    description = models.TextField()

    @property
    def short_description(self):
        return truncatechars(self.description, 100)

class FooAdmin(admin.ModelAdmin):
    list_display = ['short_description']

这篇关于使django管理员在列表结果中显示不超过100个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆