当前位置: 动力学知识库 > 问答 > 编程问答 >

Converting HTML in views to templates in Django

问题描述:

I am having trouble understanding the conversion between in-line HTML in the views.py file, and separating the HTML from the views file and putting it in the templates folder. For example, in the example from the Django Book -- http://djangobook.com/en/2.0/chapter07/

The Views.py file has the following code:

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))

How would I separate this into a Views and Templates file. This is what I currently have (but it's not working -- i.e., it renders a blank page) --

(in views.py)

 def display_meta(request):

items = request.META.items().sort()

return render_to_response('display_meta.html', {'items':items})

(in templates/display_meta.html)

<html>

<head></head>

<body>

<table>

{% for x, y in items %}

<tr>

<td>

{{x}}

</td>

<td>

{{y}}

</td>

</tr>

{% endfor %}

</table>

</body>

</html>

Thank you.

网友答案:

It's because this is line of code:

request.META.items().sort()

Is returning none. If you remove the .sort() you will see data.

In case you are wondering why, its because it sorts the dictionary itself, and returns none. To get around that do:

items  = request.META.items()
items.sort()
return render_to_response('display_meta.html', {'items':items})
分享给朋友:
您可能感兴趣的文章:
随机阅读: