I am trying pass to list from a view to template in Django.
In my file wiew.py I define the view named hour
# This Python file uses the following encoding: utf-8
from django.shortcuts import render
from django.http import HttpResponse
from datetime import datetime
from django.shortcuts import render_to_response
# Create your views here.
def hour(request):
now = datetime.now()
list = ['Bern','Bob','Eufronio','Epifanio','El pug']
return render_to_response('hour.html',list)
I'm using shorcuts in my view.
I have a template named hour.html so this way:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8">
<title>Date</title>
</head>
<body>
The names are:
{%for item in list%}
<li>{{item}}</li>
{% endfor %}
</body>
</html>
But my template hour.html is showed empty in the browser. How to can I send the list from my view to template. Thanks for tour attention
And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.
Introducing {% block %}The block tag is used to define a block that can be overridden by child templates. In other words, when you define a block in the base template, you're saying that this area will be populated with content from a different, child template file.
You should use return render_to_response('hour.html',{"list": list})
Or return render(request, 'hour.html', {"list": list})
The second render
need from django.shortcuts import render
list
is a python built-in sequence type, you should avoid using generic names for you variable names to avoid conflicts. You can read more about Python's built-in types here.
For this however, you just need to pass in the context:
return render_to_response('hour.html', {"list": list})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With