简体   繁体   English

模板中的Django渲染HTML提供字节

[英]Django Rendering HTML in a template give bytes

In my django application, I am manually rendering a page and giving it to a template to include : 在我的django应用程序中,我手动呈现页面并将其提供给模板以包括:

def get_context_data(self, **kwargs):
    page = render(self.request, test_absolute_path, context, content_type=None, status=None, using=None)
    soup = BeautifulSoup(page.content, 'html.parser')
    soup.dosomestuff()
    page.content = str(soup.decode()).replace('\n','')
    context['subtests'].append(page)
    return context

Then including the rendered HTML into a template using the safe tag : 然后使用safe标签将渲染的HTML包含到模板中:

 {{ page.content | safe }}

I do have my tags included but the text appears like a bytearray and the encoding isn't right for some reason : 我确实包含了标签,但是文本看起来像字节数组,并且由于某些原因编码不正确:

b'
My text Cat\xc3\xa9gorisation S\xc3\xa9quqsdazeences R\xc3\xa9ponses associ\xc3\xa9es Fluidit\xc3\xa9 

Notice that I also had to replace all \\n with nothing in the code. 注意,我还必须用代码中的所有内容替换所有\\n

EDIT : 编辑:

I noticed that encoding the soup in ascii at least prints all the characters, I still can't get rid of the \\n or b though : 我注意到用ascii编码汤至少可以打印所有字符,但是我仍然无法摆脱\\nb

page.content = soup.encode('ascii')

The page.content always returns byte array. page.content始终返回字节数组。 One option is to call decode in template tag. 一种选择是在模板标签中调用解码。

{{ page.content.decode | safe }}

Another one is to use different name like below. 另一个是使用不同的名称,如下所示。

def get_context_data(self, **kwargs):
    page = render(self.request, 'viewbase/sub_page.html', context,
            content_type=None, status=None, using=None)
    soup = BeautifulSoup(page.content, 'html.parser')
    soup.dosomestuff()
    page.new_content = soup.decode()
    context['subtests'].append(page)
    return context

With that, the template has below tag. 这样,模板具有以下标记。

{{ page.new_content | safe }}

Or directly put content instead of page in context in case you don't need anything else from the page. 或者,如果您不需要页面中的任何其他内容,则直接将内容而不是页面放在上下文中。

    context['subtests'].append(soup)

{{ soup | safe }}

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

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