【发布时间】:2025-12-29 05:15:10
【问题描述】:
在模板中,我需要从保存在模型实例中的 HTML 内容呈现 {{ variable }}。
以下是代码的精简部分。
page.html
{% load static %}
<html>
<head>
<styles, links, etc.>
<title>{{ object.title }}</title>
</head>
<body>
<div>{{ object.html_content }}</div>
</body>
</html>
型号
class Page(models.Model):
title = models.CharField(max_length=30)
html_content = models.TextField()
GlobalMixin
# Used site wide for Global information.
class GlobalMixin(object):
def get_context_data(self, *args, **kwargs):
context = super(GlobalMixin, self).get_context_data(*args, **kwargs)
context['variable'] = "A Global piece of information"
return context
查看
from .mixins import GlobalMixin
from .models import Page
PageView(GlobalMixin, generic.DetailView):
model = Page
template_name = "my_app/page.html"
def get_context_data(self, *args, **kwargs):
context = super(PageView, self).get_context_data(*args, **kwargs)
return context
管理和 HTML 内容字段
然后我输入 admin,添加新页面,按照以下示例将我的 HTML 内容输入到 html_content 字段“Html Content”中。
<p>This is {{ variable }} that I need to display within my rendered page!</p>
然后保存。
浏览器结果
This is {{ variable }} that I need to display within my loaded page!
我知道有 Django Flat Pages,但它看起来不适合我,因为我需要在我的模板中使用平面页面不提供的全局变量。
模板直接与模型内容一起呈现,无需查看它。 我想我需要处理视图中的 html_content 字段,然后将所需的上下文变量添加到返回的上下文中或保存一个临时模板文件,将 html_content 附加到文件中,然后渲染它。
我该怎么做?
是否有 Django 打包接口可用于在我的视图中处理模板?
【问题讨论】:
标签: html django templates views models