![](/img/trans.png)
[英]How to get model field value from model and field in django template?
[英]How to get django model field into html template?
第一次在這里發帖,是 Django 的新手,提前抱歉。
我試圖將我的 model 中的名稱字段插入我的 html 模板,然后我將其轉換為 pdf。
涉及 html 到 pdf 轉換的所有內容都在工作,我似乎無法從我的 model 中獲取名稱字段,以便在它呈現時進入 html_template。
我嘗試將 'name': name 添加到 render_to_pdf 視圖中的 context_dict 中,但這不起作用。
我認為我可能會遺漏一些東西。
pdf_template.html
{% block content %}
<div class="container">
<div class="row">
<p> **{{name}}** </p>
</div>
{% endblock %}
模型.py
class User(models.Model):
username = models.CharField(max_length = 20, primary_key=True)
name = models.CharField(max_length = 20)
def __str__(self):
return self.name
視圖.py
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
目前還不清楚你想做什么/問什么。
如果要列出所有用戶名,可以這樣做:
def listView(req):
users = User.objects.all
return render(request, 'home.html', {'names': users})
然后在您的模板中:
<div class="container">
{% for name in names%}
<p>{{ name.username }}</P
</div>
這就是您需要構建 function 並使用當前設計調用它的方式。 如果 name 為 none 或空字符串,則不會出現。
def render_to_pdf(template_src, context_dict=None):
if context_dict is None:
context_dict = {}
template = get_template(template_src)
html = template.render(context_dict)
...
render_to_pdf('template/path/...', {'name': "some name"})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.