简体   繁体   中英

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:

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. How can i render an html code in memory for display page and then destroy it?

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. 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 ,

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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