【问题标题】:Django model TextField not renderingDjango模型TextField不呈现
【发布时间】:2025-12-23 01:35:10
【问题描述】:

我一直在尝试将 TextField 的内容呈现到我的 HTML 页面上,但它是唯一拒绝呈现的内容。会不会是那个模型的继承有问题?

这是我的模型:

class Section(models.Model):
    order_id = models.IntegerField()
    SECTION_TYPE_CHOICES = (('reg', 'regular'),
                        ('not', 'note'),
                        )
    section_type = models.CharField(
        max_length=5,
        choices=SECTION_TYPE_CHOICES,
        default='reg',
    )

class TextSection(Section):
    contents = models.TextField(blank=True, max_length=5000)

class Post(models.Model):
    post_id = models.IntegerField(unique=True)
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    slug = models.CharField(unique=True, max_length=20)
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    belongs_to = models.ForeignKey('Story')
    order_id = models.IntegerField()
    contents = models.ManyToManyField(Section, blank=True)

和模板

{% extends 'stories/base.html' %}

{% block title %}
    {{ post.belongs_to.title }} | {{ post.title }}
{% endblock %}

{% block content %}
    <!-- Story Information -->
    <div>
        <h1>{{ post.title }}</h1>
        <p>by {{ post.author }} on {{  post.published_date }}</p>
    </div>
    <!-- Post Contents -->
    <div>
        {% for section in post.contents.all %}
            <div>
<!--------- Part that does not render --------->
                <p>{{ section.contents|safe }}</p>
<!--------- Part that does not render --------->
                {{ section.order_id }}

            </div>
        {% endfor %}
    </div>

{% endblock %}

它总是渲染 section.order_id 但从不渲染 section.contents

提前感谢您的任何建议。

编辑:最终删除了多态性,只是扩展了我的 Section 模型以包含各种内容。

【问题讨论】:

    标签: django django-models django-templates


    【解决方案1】:

    Post.contents 指向 Section 模型,而不是 TextSection;部分本身没有contents 字段。如果你需要这个,你应该将你的多对多字段直接指向 TextSection。

    【讨论】:

    • 如果我向 Section 添加内容字段,TextSection 会覆盖它吗?我希望将来能够添加 ImageSection 或 VideoSection。
    • 这个想法是让内容包含不同类型的部分,如果这有意义的话。
    • 感谢您的回答,我最终放弃了多态性,只是扩展了我的 Section 模型。