简体   繁体   English

从 Django 中的 db 字段渲染 html

[英]Render html from a db field in Django

In my django project I have a model with a field that contain html code as text:在我的 django 项目中,我有一个 model 字段,其中包含 html 代码作为文本:

html_test = models.TextField()

for example in this field could be:例如在这个领域可能是:

<html>
    <header><title>This is title</title></header>
    <body>
        Hello world
    </body>
</html>

I want to retrive this code and render dynamically showing the corresponding html page without create a file or save it on disk.我想检索此代码并动态呈现显示相应的 html 页面,而无需创建文件或将其保存在磁盘上。 How can i render an html code in memory for display page and then destroy it?如何在 memory 中渲染 html 代码以显示页面,然后将其销毁?

I'm still not sure what your actual question is.我仍然不确定你的实际问题是什么。 You retrieve the model from the db and return the data to the user, just like anything else.您从数据库中检索 model 并将数据返回给用户,就像其他任何事情一样。 For example, a view might look like this:例如,视图可能如下所示:

def my_view(request, pk):
    obj = MyModel.objects.get(pk=pk)
    return HttpResponse(obj.html_test)

Using jinja2 as the templating engine ,使用 jinja2 作为模板引擎

class YourClassName(generic.TemplateView):
    template_name = 'your_template.jinja'

    def get_context_data(self, **kwargs):
        kwargs['html_data'] = MyModel.objects.get(pk=pk).html_test
        return super(YourClassName, self).get_context_data(**kwargs)

In your your_template.jinja在你的 your_template.jinja

<html>
<header><title>This is title</title></header>
<body>
    {{html_data}}
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM