Django模型TextField无法渲染

时间:2017-11-16 14:46:03

标签: django django-models django-templates

我一直在尝试将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模型以包含各种内容。

1 个答案:

答案 0 :(得分:0)

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