Django admin realizes the normal display of TextField field, changelist page line feed and spaces

Problem background

After binding the model with admin view in Django background, you can easily add, delete, query and modify the underlying data table through the web page.
In practice, some data fields will store json or other text contents containing line breaks and spaces. These text contents can normally display line breaks and spaces on the record editing details page, as follows:

However, on the changelist page, all spaces and line breaks will be omitted, resulting in poor readability, as follows:

reason

The reason is that on the edit details page, the label for storing text is textarea. The text content in this label will not ignore line breaks and space characters. You can see the following code by using the browser developer tool:

<textarea name="lang_content" cols="40" rows="10" class="vLargeTextField" required="" id="id_lang_content">{
  "en": "this is a content",
  "zh-hant": "This is the default body content"
}</textarea>

On the changelist page, the td tag is used by default, that is, it is directly put into a table cell. At this time, all continuous spaces and line breaks will be treated as a single space according to the HTML standard:

<td class="field-lang_content">{
  "en": "this is a content",
  "zh-hant": "This is the default body content"
}</td>

Solution

With a simple test_ Take the admin view of record table as an example.
Table structure:

CREATE TABLE `test_table` (
  `id` bigint(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Auto increment primary key',
  `title` varchar(255) NOT NULL DEFAULT '0',
  `content` varchar(255) NOT NULL,
  `lang_content` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

models.py:

# coding=utf-8
from django.db import models


class TestRecord(models.Model):
    class Meta:
        db_table = "test_record"
        db_tablespace = 'test_db'

    id = models.AutoField(primary_key=True, verbose_name="id")
    title = models.CharField(max_length=255)
    content = models.CharField(max_length=255)
    lang_content = models.TextField()

admin.py

from django.contrib import admin
from django.utils.html import format_html

from .models import TestRecord


@admin.register(TestRecord)
class TestRecordAdmin(admin.ModelAdmin):
    list_display = ('id', 'title', 'content', 'lang_content', 'lang_content_view')

Use list_editable

Will Lang_ Put content into the list_editable, as follows:

    list_editable = ('lang_content', )

In this way, on the change list page, Lang will be decorated with the textarea tag_ Content, so spaces and line breaks can be displayed correctly:

At the same time, Lang can be edited directly on the changelist page_ The content field cannot meet the requirement that the field can only be read on the changelist page and cannot be edited. Therefore, the editing function and display function are forcibly bound, which cannot be separated and lacks flexibility.

Use format_html -- meet read-only requirements

In Django utils. A format is provided in HTML_ HTML function, which can be used to escape and render all output content in HTML format.
Therefore, you can define an admin class that is specifically responsible for displaying Lang_ Instance method of content, lang_content content is wrapped with pre or textarea tags, and then formatted_ Return after HTML escape. This method is more flexible. You can also customize the output effect by adjusting each attribute of the label, such as setting the height (rows), width (cols), etc.
The code is shown below

    def lang_content_view(self, obj):
        # return format_html('<textarea cols=40 rows={} readonly>{}</textarea>', obj.lang_content.count('\n')+1, obj.lang_content)
        return format_html('<pre>{}</pre>', obj.lang_content)

The display effect is as follows:

The corresponding web page code is as follows:

<td class="field-lang_content_view"><pre>{
  "en": "this is a content",
  "zh-hant": "This is the default body content"
}</pre></td>

Please indicate the source and original address for Reprint: https://www.cnblogs.com/AcAc-t/p/django_admin_changelist_textfield_newline_display.html

Keywords: Python Django html admin

Added by sabien on Mon, 03 Jan 2022 19:47:46 +0200