我有一个基本的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
那么,有可能以某种方式更改它吗?