我是Django的新手,我想请一点帮助。 我在views.py
中有这段代码def display_meta(request):
values = request.META.items()
values.sort
html = []
for k, v in values:
html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
return HttpResponse('<table>%s</table>' % '/n'.join(html))
-------返回渲染(HttpResponse,'current_datetime.html',{'about':html})
def current_datetime(request):
now = datetime.datetime.now()
return render(request, 'current_datetime.html', {'current_date': now})
带有'------'的部分由我添加,但我不知道是否可以。问题在于,如何在html文件中显示返回HttpResponse以显示用户使用的元素。
{% extends "base.html" %}
{% block title %}The current time{% endblock %}
{% block content %}
<p>It is now {{ current_date }}.</p>
<p>You are using {{ HERE WILL BE DISPLAYED THE META FUNCTION, BUT HOW ??? }}</p>
{% endblock %}
{% block footer %}
<hr>
<p>Thanks for visiting my site.</p>
{% endblock %}
我无法理解如何...... 谢谢你们在advence!
答案 0 :(得分:1)
在settings.py中添加read what this mean
TEMPLATE_CONTEXT_PROCESSORS = (
...,
'django.core.context_processors.request',
)
然后,加载自定义模板标签非常重要
{% extends "base.html" %}
# NEW LINE
{% load custom_tags %}
{% block title %}The current time{% endblock %}
{% block content %}
<p>It is now {{ current_date }}.</p>
<p>You are using {{ request|extract_meta }}</p>
{% endblock %}
{% block footer %}
<hr>
<p>Thanks for visiting my site.</p>
{% endblock %}
创建名为extract_meta
here is doc
在templatetags / custom_tags.py中:
from django import template
register = template.Library()
@register.filter(name="extract_meta")
def extract_meta(request):
values = request.META.items()
values.sort
html = []
for k, v in values:
html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
return '<table>%s</table>' % '/n'.join(html)