如何更改Django的template.source以呈现HTML内容的一部分

时间:2019-06-16 13:04:43

标签: django django-templates

我有一个基本的Django HTML模板:

<html>
<head>...</head>
<body>

    <div id="products">

        <div>Product 1</div>
        <div>Product 2</div>

    </div>

</body>
</html>

我只需要返回div[id="products"]views.py的内容

因此,我已经在views.py中尝试过此操作:

from django.http import HttpResponse
from django.template.loader import get_template

from lxml import etree
from lxml.html import fromstring

def products(request):

    template = get_template('products/products.html')

    tree = fromstring(template.template.source)

    el = tree.xpath('//div[@id="products"]')[0]

    template.template.source = etree.tostring(el).decode('utf-8')

    print(template.template.source)
    // Prints exactly what I need
    // <div>Product 1</div>
    // <div>Product 2</div>

    content = template.render({}, request)

    print(content)
    // Prints full rendered products.html's HTML

    return HttpResponse(content)

当然,页面还会呈现完整的模板

似乎无法重新定义template.source

那么,有可能以某种方式更改它吗?

0 个答案:

没有答案